-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTest6-Move To Last
62 lines (56 loc) · 1.49 KB
/
Test6-Move To Last
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
Given a linked list and a key in it, the task is to move all occurrences of given key to end of linked list, keeping order of all other elements same.
Return the updated head of LL.
Input Format :
Line 1 : Elements of the linked list ending with -1 (-1 not included)
Line 2 : Key n, Element which has to shifted
Output Format :
Updated linked list
Constraints :
1 <= size of list <= 100
Sample Input 1:
1 2 2 3 4 5 -1
2
Sample Output 1:
1 3 4 5 2 2
Sample Input 2:
1 1 2 3 4 -1
1
Sample Output 2:
2 3 4 1 1
*****************************************Code****************************************
public class Solution {
public static Node<Integer> func(Node<Integer> head,int n) {
if(head==null || head.next==null)
return head;
Node<Integer> tail=head,prev=null,curr=head;
int cnt=0;
while(tail.next!=null)
{
tail=tail.next;
}
Node<Integer> oldTail=tail;
while(curr.next!=oldTail)
{
if(curr.data==n)
{
tail.next=new Node<>(n);
tail=tail.next;
if(prev==null)
{
curr=curr.next;
head=curr;
}
else
{
prev.next=prev.next.next;
curr=prev.next;
}
}
else{
prev=curr;
curr=curr.next;
}
}
return head;
}
}