[Leetcode] Swap nodes in pairs 成对交换结点
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4, you should return the list as2->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.
题意:成对交换结点。
思路:这题感觉是reverse nodes in k grops的是一个特殊情况。这题更简单一些,只要保证当前结点cur和其后继存在就可以交换。改变表头,所以要new一个。代码如下:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *swapPairs(ListNode *head) 12 { 13 ListNode *nList=new ListNode(-1); 14 nList->next=head; 15 ListNode *pre=nList; 16 ListNode *cur=head; 17 18 while(cur&&cur->next) 19 { 20 ListNode *temp=cur->next; 21 cur->next=temp->next; 22 temp->next=pre->next; 23 pre->next=temp; 24 pre=cur; 25 cur=cur->next; 26 } 27 28 return nList->next; 29 } 30 };