1. 程式人生 > >求未知長度單鏈表中倒數第k個節點

求未知長度單鏈表中倒數第k個節點

問題如下:單鏈表,不知道長度,如何得到它的倒數第k個節點。

方法是:先從第一個結點S開始,走到k個節點到D,再同時移動S和D,直到D到尾巴D`,那麼此時的S就是倒數第k個節點

class LinkedList
    {
        private LinkNode predix = new LinkNode(){next = null};

        public void Insert(int val)
        {
            LinkNode current = predix;
            while (current.next != null)
            {
                current = current.next;
            }
            current.next = new LinkNode(){value = val,next = null};
        }

        public void Show()
        {
            LinkNode current = predix.next;
            while (current != null)
            {
                Console.WriteLine(current.value);
                current = current.next;
            }
        }

        public LinkNode Back_K(int k)
        {
            if(k<=0)
                throw new Exception("k值不正確");

            LinkNode node = predix;
            for(int i=0;i < k;i++)
            {
                node = node.next;
            }
            if(node==null)
                throw  new Exception("沒有");
            else
            {
                LinkNode headNode = predix;
                while (node!=null)
                {
                    node = node.next;
                    headNode = headNode.next;
                }
                return headNode;
            }
        }
    }

    class LinkNode
    {
        public int value;
        public LinkNode next;
    }