8. Move last element to the front of the linked list

8. Move last element to the front of the linked list


Problem link :- click here


package Linked_List;

public class LinkedList__8
{

	//We have to move the last node to the first and we should make that head
	static void moveLastToFirst(LinkedList list)
	{
		Node first, last, last_sec=null;
		first = list.head;
		
		for(last=list.head; last.next!=null; last=last.next)
		{
			last_sec = last;
		}
		
		//here last_sec is the last second node which has to be the last element now
		last.next = first;
		list.head = last;		//very important step
		last_sec.next = null;
	}
	
	public static void main(String[] args)
	{
		LinkedList list = new LinkedList();
		list.push(1);
		list.push(2);
		list.push(2);
		list.push(3);
		list.push(3);
		list.push(4);
		
		System.out.println("Linked list : ");
		printList(list);
		
		moveLastToFirst(list);
		System.out.println("Linked list after moving last node : ");
		printList(list);
	}

	static void printList(LinkedList list)
	{
		for(Node temp=list.head; temp!=null; temp=temp.next)
			System.out.print(temp.data + "-> ");
		System.out.println("null");
	}
}

Time complexity :- O(n)
Space complexity :- O(1)

Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree