-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathSwapAdjacentNodes.java
More file actions
27 lines (26 loc) · 826 Bytes
/
SwapAdjacentNodes.java
File metadata and controls
27 lines (26 loc) · 826 Bytes
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
/**
* Definition for singly-linked list.
* class ListNode {
* public int val;
* public ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
// Take a Linked List & swap adjacent nodes of the linkedList
public class Solution {
public ListNode swapPairs(ListNode A) {
ListNode temp = new ListNode(0);
temp.next = A;
ListNode currentNode = temp;
while(currentNode.next != null && currentNode.next.next != null)
{
ListNode firstNode = currentNode.next;
ListNode secondNode = currentNode.next.next;
firstNode.next = secondNode.next;
currentNode.next = secondNode;
currentNode.next.next = firstNode;
currentNode = currentNode.next.next;
}
return temp.next;
}
}