码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode24]Swap Nodes in Pairs

时间:2016-01-22 22:09:51      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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.

交换链表相邻结点

思路:只要保存头结点,然后理清交换结点位置就好了

  例如链表现在是1->2->3->4,head指向1,新建一个结点root,root->next指向head

第一次循环:pre指向root,要交换12,首先保存2的下一个结点3,接下来让pre->next为2,2的next为1,1的next为刚才保存的3,然后让head指向3,pre指向1就好了,然后继续 

代码:

/**
 * 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 *root = new ListNode(0);
        root->next = head;
        ListNode *pre = root;
        while(head && head->next)
        {
            ListNode* tmp = head->next->next;
            pre->next = head->next;
            pre->next->next = head;
            head->next = tmp;
            pre = head;
            head = head->next;
        }
        return root->next;
    }
};

 

[LeetCode24]Swap Nodes in Pairs

标签:

原文地址:http://www.cnblogs.com/zhangbaochong/p/5152169.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!