Swap Nodes in Pairs

Description:

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.

Code:

 1   ListNode* swapPairs(ListNode* head) {
 2         if (!head)
 3             return NULL;
 4         ListNode *preNode = new ListNode(0);
 5         preNode ->next = head;
 6         
 7         ListNode *m_preNode = preNode;
 8         ListNode *p = head;
 9         ListNode *q = p->next;
10         
11         while (p&&q)
12         {
13             preNode->next = q;
14             p->next = q->next;
15             q->next = p;
16           
17             preNode = p;
18             p = preNode->next;
19             //要注意检测p是否为空值,否则对q赋值就会出现错误
20             if (p)
21                 q = p->next;
22             else
23                 q = NULL;
24         }
25       return m_preNode->next;
26     }

Swap Nodes in Pairs_第1张图片

你可能感兴趣的:(node)