Contents

/*

  • Given a linked list, swap every two adjacent nodes and return its head.

  • For example,

  • Given 1->2->3->4, you should return the list as 2->1->4->3.

  • Your algorithm should use only constant space. You may not modify the

  • values in the list, only nodes itself can be changed.
    /
    /*
  • Definition for singly-linked list.
  • public class ListNode {
  • int val;
  • ListNode next;
  • ListNode(int x) {
  • val = x;
  • next = null;
  • }
  • }
    */
  • 一对一对的交换位置
  • 另开一个空的新头结点来辅助
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {  
public:
ListNode *swapPairs(ListNode *head) {
ListNode *newHead = new ListNode(0);
newHead->next = head;
ListNode *preNode = newHead, *curNode = head;
int cnt = 1;
while (curNode != NULL && curNode->next != NULL) {
// swap curNode and curNode->next
preNode->next = curNode->next;
curNode->next = preNode->next->next;
preNode->next->next = curNode;

// go over two nodes
preNode = curNode;
curNode = curNode->next;
}
head = newHead->next;
delete newHead;
return head;
}
};
Contents