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

Leetcode:Swap Nodes in Pairs 链表成对交换节点

时间:2014-06-13 17:04:27      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   java   

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.

 

解题分析:

思路很简单,需要注意:

1. 链表第一个节点也可能被修改,存在 链表头节点操作和其余结点操作不统一的情况,我们虚拟一个前置结点指向链表的第一个节点

2. 防止断链,多用暂存结点

bubuko.com,布布扣
class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        if (head == nullptr) return nullptr;
        ListNode* newHead = new ListNode(0);
        newHead->next = head;
        
        ListNode* cur = newHead;
        while (cur != nullptr && cur->next != nullptr && cur->next->next != nullptr) {
            ListNode* first = cur->next;
            ListNode* second = cur->next->next;
            ListNode* nextNode = second->next;
            cur->next = second;
            cur->next->next = first;
            cur = cur->next->next;
            cur->next = nextNode; // 防止断链
        }
        return newHead->next;
    }
};
bubuko.com,布布扣

 

Leetcode:Swap Nodes in Pairs 链表成对交换节点,布布扣,bubuko.com

Leetcode:Swap Nodes in Pairs 链表成对交换节点

标签:des   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/wwwjieo0/p/3784632.html

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