Today we will write a program for appending last N nodes from the beginning to the start of the link list.

Example

input linked is 0->1->2->3->4->5->6->7->8->9 and the value of N is 3 than output must be

7->8->9->0->1->2->3->4->5->6

Code

        public void AppendLastNNodeToHead(Node<T> root, int n)
        {
            Node<T> currentNode = root;
            Node<T> previousNode = root;

            for (int i = 0; i < n; i++)
            {
                currentNode = currentNode.Next;
                if (currentNode == null)
                {
                    Console.WriteLine("List has less number of nodes");
                    return;
                }
            }

            while (currentNode.Next != null)
            {
                currentNode = currentNode.Next;
                previousNode = previousNode.Next;
            }

            currentNode.Next = root;
            root = previousNode.Next;
            previousNode.Next = null;

            this.head = root;
        }