Skip to content

Commit 11d6214

Browse files
authored
Create LinkedList-Swap two Nodes of LL
1 parent 924a3e5 commit 11d6214

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

LinkedList-Swap two Nodes of LL

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
You have been given a singly linked list of integers along with two integers, 'i,' and 'j.' Swap the nodes that are present at the 'i-th' and 'j-th' positions.
2+
Note :
3+
Remember, the nodes themselves must be swapped and not the datas.
4+
5+
No need to print the list, it has already been taken care. Only return the new head to the list.
6+
Input format :
7+
The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
8+
9+
The first line of each test case or query contains the elements of the singly linked list separated by a single space.
10+
11+
The second line of input contains two integer values 'i,' and 'j,' respectively. A single space will separate them.
12+
Remember/consider :
13+
While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element
14+
Output format :
15+
For each test case/query, print the elements of the updated singly linked list.
16+
17+
Output for every test case will be printed in a seperate line.
18+
Constraints :
19+
1 <= t <= 10^2
20+
0 <= M <= 10^5
21+
Where M is the size of the singly linked list.
22+
0 <= i < M
23+
0 <= j < M
24+
25+
Time Limit: 1sec
26+
Sample Input 1 :
27+
1
28+
3 4 5 2 6 1 9 -1
29+
3 4
30+
Sample Output 1 :
31+
3 4 5 6 2 1 9
32+
Sample Input 2 :
33+
2
34+
10 20 30 40 -1
35+
1 2
36+
70 80 90 25 65 85 90 -1
37+
0 6
38+
Sample Output 2 :
39+
10 30 20 40
40+
90 80 90 25 65 85 70
41+
42+
************************************************Code************************************************
43+
public static LinkedListNode<Integer> swapNodes(LinkedListNode<Integer> head, int i, int j) {
44+
45+
LinkedListNode<Integer> temp=head,prev=null,c1=null,c2=null,p1=null,p2=null;
46+
int pos=0;
47+
if(i==j)
48+
return head;
49+
while(temp!=null)
50+
{
51+
if(pos==i)
52+
{
53+
p1=prev;
54+
c1=temp;
55+
}
56+
else if(pos==j)
57+
{
58+
p2=prev;
59+
c2=temp;
60+
}
61+
prev=temp;
62+
temp=temp.next;
63+
pos++;
64+
}
65+
if(p1!=null)
66+
{
67+
p1.next=c2;
68+
}
69+
else{
70+
head=c2;
71+
}
72+
if(p2!=null){
73+
p2.next=c1;
74+
}
75+
else{
76+
head=c1;
77+
}
78+
LinkedListNode<Integer> temp1=c2.next;
79+
c2.next=c1.next;
80+
c1.next=temp1;
81+
return head;
82+
}

0 commit comments

Comments
 (0)