【LeetCode】024. Swap Nodes in Pairs

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.

 

题解:

  没什么好写的,链表题一般要注意头结点的问题,还有一定要画图!

Solution 1

 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         ListNode dummy(-1);
13         dummy.next = head;
14         ListNode* cur = &dummy;
15         
16         while (cur->next && cur->next->next) {
17             ListNode* tmp = cur->next->next;
18             cur->next->next = tmp->next;
19             tmp->next = cur->next;
20             cur->next = tmp;
21             cur = tmp->next;
22         }
23         
24         return dummy.next;
25     }
26 };

 

  递归:

Solution 2

 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         if (!head || !head->next)
13             return head;
14         ListNode* newHead = head->next;
15         head->next = swapPairs(head->next->next);
16         newHead->next = head;
17         return newHead;
18     }
19 };

 

posted @ 2018-03-25 22:07  Vincent丶丶  阅读(141)  评论(0编辑  收藏  举报