Given a circular linked list consisting of N nodes and an integer K, your task is to add the integer K at the end of the list.
Input
The first line contains an integer N, the length of the circular linked list.
The next line contains N integers, the elements of the circular linked list.
Constraints:
1 <= N <= 1000
1 <= list[i] <= 1000, where list[i] is the ith element of the list.
Output
Print the updated circular linked list in new line.
Example
Input:
3 1 2 3 4
Output:
1 2 3 4
Input:
4 1 2 3 4 1
Output:
1 2 3 4 1
Solution:–
import java.util.*; import java.lang.*; import java.io.*; public class Main { Node head=null; Node tail=null; class Node{ int data; Node next; Node(int data) { this.data = data; next = null; } } public void add(int data) { Node newNode = new Node(data); if(head==null) { head=newNode; tail=newNode; return; } else{ tail.next=newNode; tail=newNode; tail.next=head; } } void addLast(int x) { Node newNode = new Node(x); Node temp=head; while(temp.next!=head) { temp=temp.next; } temp.next=newNode; newNode.next=head; } public void printList() { Node temp=head; while(temp.next!=head) { System.out.print(temp.data+" "); temp=temp.next; } System.out.print(temp.data); } public static void main (String[] args) throws java.lang.Exception { //your code here Main m = new Main(); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for(int i=0;i<n;i++) { int value=sc.nextInt(); m.add(value); } int k =sc.nextInt(); m.addLast(k); m.printList(); } }
Add a Comment