[LeetCode]Swap Nodes in Pairs

来源:互联网 发布:windows重置此电脑失败 编辑:程序博客网 时间:2024/05/29 04:22

题目

Number: 24
Difficulty: Medium
Tags: Linked List

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.

题解

链表中每两个结点交换。

不允许改变值。比较简单,注意边界处理。

代码

非递归:

ListNode* swapPairs(ListNode* head) {    ListNode* p = head;    ListNode* pre = p;    if(!p)        return head;    while(p && p->next)    {        ListNode* q = p->next;        p->next = q->next;        q->next = p;        if(p == head)            head = q;        else            pre->next = q;        pre = p;        p = p->next;    }    return head;}

递归:

ListNode* swapPairs(ListNode* head) {    ListNode* p = head;    if(!p || !p->next)        return head;    p = head->next;    head->next = swapPairs(p->next);    p->next = head;    return p;}
0 0