您的位置:首页 > 其它

LeetCode——024

2016-04-16 12:07 281 查看


/*

24. Swap Nodes in Pairs My Submissions QuestionEditorial Solution

Total Accepted: 92808 Total Submissions: 264576 Difficulty: Easy

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

*/

/*

解题思路:

关于链表的题是比较容易的,只要在纸上画一画就可以了。此题要交换奇偶位置的节点,游标指针一次跳两格呗。单链表的操作都是拿着要变化节点的前一个节点来控制的。所以我们先增加一个临时头结点dummy(这个节点对于链表的操作百试不爽啊!)。

1.判断链表节点个数<2则直接返回

2.在循环开始要判断我们要交换的下两个节点是不是存在即p->next 和p->next->next ,这是能继续循环的必要条件

3.下一轮p应该在上一轮的p->next位置。依次这样下去就好了,如果理不清的话现在纸上画画吧。

*/

/**
* 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==NULL || head->next==NULL)return head;
ListNode* dummy=new ListNode(-1);
dummy->next=head;
ListNode* p=dummy;

while(p->next && p->next->next){

ListNode *tmp=p->next;
p->next=tmp->next;
tmp->next=p->next->next;;
p->next->next=tmp;
p=tmp;
}
return dummy->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: