[leetcode] 【链表】24. Swap Nodes in Pairs

原创 2016年06月01日 22:01:05

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变成 2->1->4->3

题解

略··看代码吧

/**
 * 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 newhead(-1);
        newhead.next=head;
        ListNode *prev=&newhead,*cur=head,*next=head->next;
        while(cur&&next)
        {
            cur->next=next->next;
            next->next=cur;
            prev->next=next;
            prev=cur;
            cur=cur->next;
            if(cur==NULL)
                break;
            next=cur->next;
        }
        return newhead.next;
    }
};



版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode解题之24. Swap Nodes in Pairs java 版(成对翻转链表)

leetcode解题之24. Swap Nodes in Pairs java 版(成对翻转链表)

【LeetCode-面试算法经典-Java实现】【024-Swap Nodes in Pairs(成对交换单链表的结点)】

【024-Swap Nodes in Pairs(成对交换单链表的结点)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given a linked list, swap...

LeetCode | Swap Nodes in Pairs(将链表中的元素两两交换)

Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2-...

LeetCode之24----Swap Nodes in Pairs

题目: Given a linked list, swap every two adjacent nodes and return its head. For example, Gi...

[leetcode: Python]24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.For example, Given 1->2->3->...
  • NXHYD
  • NXHYD
  • 2017年05月19日 15:37
  • 163

LeetCode 24. Swap Nodes in Pairs

题目Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2...
  • louisia
  • louisia
  • 2017年05月04日 11:41
  • 85

leetcode-24 Swap Nodes in Pairs

问题描述地址:https://leetcode.com/problems/swap-nodes-in-pairs/ 描述: Given a linked list, swap every two...

LeetCode OJ-24-Swap Nodes in Pairs

题目:Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2...

LeetCode24. Swap Nodes in Pairs

LeetCode24. Swap Nodes in Pairs

( Leetcode 24) Swap Nodes in Pairs

题目:Swap Nodes in Pairs Given a linked list, swap every two adjacent nodes and return its head. ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:[leetcode] 【链表】24. Swap Nodes in Pairs
举报原因:
原因补充:

(最多只允许输入30个字)