-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path24.SwapPairs.cs
39 lines (38 loc) · 1.04 KB
/
24.SwapPairs.cs
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
// 24. Swap Nodes in Pairs
// Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution
{
//intuio
public ListNode SwapPairs(ListNode head)
{
ListNode prev, curr;
prev = curr = head;
if (head == null)
return null;
if (head.next == null)
return head;
head = head.next;
while (curr != null && curr.next != null)
{
//swap
prev.next = curr.next;
prev = curr;
curr = curr.next;
prev.next = curr.next;
curr.next = prev;
curr = curr.next.next;
}
return head;
}
}