题目描述:

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.

解题思路:

把head前再加上一个节点pre代表要换位置的两个节点的前一个节点,然后循环遍历整个链表就行了。

代码:

 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* pre = new ListNode(0);
13         pre->next = head;
14         ListNode* h = pre;
15         while(pre->next&&pre->next->next){
16             ListNode* t = pre->next;
17             pre->next = t->next;
18             t->next = t->next->next;
19             pre->next->next=t;
20             pre = pre->next->next;
21         }
22         return h->next;
23     }
24 };

 

 

 

posted on 2018-02-26 00:17  宵夜在哪  阅读(88)  评论(0编辑  收藏  举报