设为首页 加入收藏

TOP

Leetcode: 24. Swap Nodes in Pairs
2017-10-12 18:00:41 】 浏览:6911
Tags:Leetcode: 24. Swap Nodes Pairs

Description

Given a linked list, swap every two adjacent nodes and return its head.

Example

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.

思路

  • 首先使用两个指针指向要交换的节点,并且使用另外一个指针用来连接两对交换节点,也就是代码中的pre
  • 考虑好边界情况吧。算是个细心活

代码

/**
 * 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) {
        ListNode *res = NULL, *ptr = NULL, *cur = NULL, *pre = NULL;
        if(!head || !head->next) return head;
        
        ptr = head;
        cur = head->next;
        while(ptr && cur){
            //剩下链表的头结点
            head = cur->next;
            
            //交换
            cur->next = ptr;
            ptr->next = head;
            
            //头结点
            if(!res)
                res = cur;
            
            //前面交换的后一个接上后面交换的前一个
            if(!pre)
                pre = ptr;
            else{
                pre->next = cur;
                pre = ptr;
            }
                
    
            ptr = head;
            if(head)
                cur = head->next;
        }
        
        return res;
    }
};
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Leetcode: 23. Merge k Sorted Li.. 下一篇Leetcode: 29. Divide Two Intege..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目