Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 46 additions & 36 deletions Linked List 2:Swap two Node of LL
Original file line number Diff line number Diff line change
@@ -1,44 +1,54 @@
public class Solution
{
public static LinkedListNode<Integer> swap_nodes(LinkedListNode<Integer> head,int i,int j)
{
LinkedListNode<Integer> temp=head,prev=null,c1=null,c2=null,p1=null,p2=null;
int pos=0;
while(temp!=null)
{
if(pos==i)
{
p1=prev;
c1=temp;
// class Node<T> {
// T data;
// Node<T> next;

// public Node(T data) {
// this.data = data;
// }
// }

public class Solution {

public static Node<Integer> swapNodes(Node<Integer> head, int i, int j) {
// Check if i and j are the same
if (i == j) {
return head;
}

Node<Integer> temp = head, prev = null, c1 = null, c2 = null, p1 = null, p2 = null;
int pos = 0;

while (temp != null) {
if (pos == i) {
p1 = prev;
c1 = temp;
} else if (pos == j) {
p2 = prev;
c2 = temp;
}
else if(pos==j)
{
p2=prev;
c2=temp;
}
prev=temp;
temp=temp.next;
prev = temp;
temp = temp.next;
pos++;
}
if(p1!=null)
{
p1.next=c2;
}
else{
head=c2;
}
if(p2!=null){
p2.next=c1;

if (p1 != null) {
p1.next = c2;
} else {
head = c2;
}
else{
head=c1;

if (p2 != null) {
p2.next = c1;
} else {
head = c1;
}
LinkedListNode<Integer> temp1=c2.next;
c2.next=c1.next;
c1.next=temp1;
return head;
}
}

Node<Integer> temp1 = c2.next;
c2.next = c1.next;
c1.next = temp1;

return head;
}

// Utility method to print the linked list
}