How to find nth element from the end of a singly linked list?

后端 未结 28 1083
感动是毒
感动是毒 2020-12-04 06:08

The following function is trying to find the nth to last element of a singly linked list.

For example:

If the elements are

相关标签:
28条回答
  • 2020-12-04 06:27

    Solution in C#. Create a LinkedList with dummy values.

      LinkedList<int> ll = new LinkedList<int>();
                ll.AddFirst(10);
                ll.AddLast(12);
                ll.AddLast(2);
                ll.AddLast(8);
                ll.AddLast(9);
                ll.AddLast(22);
                ll.AddLast(17);
                ll.AddLast(19);
                ll.AddLast(20);
    

    Create 2 pointers p1 & p1 which point to the First Node.

            private static bool ReturnKthElement(LinkedList<int> ll, int k)
            {
                LinkedListNode<int> p1 = ll.First;
                LinkedListNode<int> p2 = ll.First;
    

    Iterate through the loop till either p2 is null - which means linkedlist length is less than Kth element OR till the Kth element

                for (int i = 0; i < k; i++)
                {
                    p2 = p2.Next;
                    if (p2 == null)
                    {
                        Console.WriteLine($"Linkedlist is smaller than {k}th Element");
                        return false;
                    }
                }
    

    Now, iterate both the pointers till p2 is null. Value containted in p1 pointer will correspond to Kth Element

    
                while (p2 != null)
                {
                    p1 = p1.Next;
                    p2 = p2.Next;
                }
                //p1 is the Kth Element
                Console.WriteLine($"Kth element is {p1.Value}");
                return true;
            }
    
    0 讨论(0)
  • 2020-12-04 06:28

    You can also solve the above problem using hash tables.The entries of the hash table are position of node and address of node. So if we want to find the nth node from the end(this means m-n+1 from the first where m is number of nodes).Now when we enter the hash table entries we get the number of nodes.Steps are:-

    1.Traverse each node and make corresponding entries in hash table.

    2.Look for the m-n+1 node in hash table we get the address.

    Time complexity is O(n).

    0 讨论(0)
  • 2020-12-04 06:28

    can you use extra data structure .. if so it will be simple ... start pushing all the nodes to a stack, maintain a counter a pop it. as per your example, 8->10->5->7->2->1->5->4->10->10 start reading the linked list and start pushing the nodes or the node->data onto a stack. so the stack will look like top->{10, 10,4, 5, 1, 2, 7, 5, 10, 8}<-bottom.

    now start popping from the top of the stack maintaining a counter=1 and every time you pop increase the counter by 1, when you reach n-th element (in your example 7th element) stop popping.

    note: this will print or retrieve the data/nodes in reverse order

    0 讨论(0)
  • 2020-12-04 06:29

    Just another solution to this problem. Though the time complexity remains the same, this code achieves the solution in a single loop.

    public Link findKthElementFromEnd(MyLinkedList linkedList, int k)
        {
            Link current = linkedList.getFirst();//current node
            Link currentK = linkedList.getFirst();//node at index k
    
            int counter = 0;
    
            while(current.getNext()!=null)
            {
                counter++;
    
                if(counter>=k)
                {
                    currentK = currentK.getNext();
                }
    
                current = current.getNext();
            }
    
            //reached end
            return currentK;
        }
    
    0 讨论(0)
  • 2020-12-04 06:30

    The problem given in the career cup book is slightly different. It says find the nth to last element of a singly linked list.

    Here is my code:

        public void findntolast(int index)
        {
            Node ptr = front; int count = 0;
            while(ptr!=null)
            {
                count++;
                if (count == index)
                {
                    front = ptr;
                    break;
                }
                ptr = ptr.next;
            }
            Node temp=front;
            while(temp!=null)
            {
                Console.WriteLine(temp.data);
                temp=temp.next;
            }
        }
    
    0 讨论(0)
  • 2020-12-04 06:31

    I have my recursive solution at another thread in StackOverflow here

    0 讨论(0)
提交回复
热议问题