您的位置:首页 > Web前端 > Node.js

Swap Nodes in Pairs

2017-01-11 00:10 344 查看
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.

Subscribe to see which companies asked this question
这道题,要了解链表之间的插入和调换,要交换两个指针,需要三个指针(需要一个头指针,两个节点各一个指针),这是必须要知道的。而且由于head指针里有数据,所以必须创建一个空指针将连接head,这个空指针作为第一次循环的头指针。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head)
return head;
ListNode new_head(-1);
new_head.next=head;
ListNode* N=&new_head;
ListNode* p=N->next;
ListNode* q=N->next->next;

while(q&&p){

N->next=q;
p->next=q->next;
q->next=p;
if(p->next){
N=N->next->next;
p=N->next;
q=N->next->next;
}
else
break;
}
return new_head.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode 刷题 算法