1.3.19

上次更新:2019-04-17
发现了题解错误/代码缺陷/排版问题?请点这里:如何:提交反馈

解答

建立一个结点引用 Cur,让它移动到尾结点的前一个结点,让那个结点的 next 变为 null。

代码

using System;
using Generics;

namespace _1._3._19
{
    /*
     * 1.3.19
     * 
     * 给出一段代码,删除链表的尾结点,其中链表的首结点为 first。
     * 
     */
    class Program
    {
        static void Main(string[] args)
        {
            Node<string> first = new Node<string>()
            {
                item = "first"
            };
            Node<string> second = new Node<string>()
            {
                item = "second"
            };
            Node<string> third = new Node<string>()
            {
                item = "third"
            };

            first.next = second;
            second.next = third;
            third.next = null;

            Node<string> current = first;
            while (current != null)
            {
                Console.Write(current.item + " ");
                current = current.next;
            }

            DeleteLast(first);
            Console.WriteLine();

            current = first;
            while (current != null)
            {
                Console.Write(current.item + " ");
                current = current.next;
            }
            Console.WriteLine();
        }

        static void DeleteLast(Node<string> first)
        {
            Node<string> current = first;

            while (current.next.next != null)
            {
                current = current.next;
            }

            current.next = null;
        }
    }
}

另请参阅

Generics 库

上一题 下一题