24. Swap Nodes in Pairs #Linked List (Easy)

Problem:

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.

Solution:

//recursive solution
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == NULL || head->next == NULL) return head;
        ListNode* next = head->next;
        head->next = swapPairs(head->next->next); //important
        next->next = head;
        head = next; 
        return head;      
    }
};
// copy
// iterative solution with dummy node
ListNode *swapPairs(ListNode *head) {
    ListNode *dummy = new ListNode(0), *node;
    node = dummy;
    dummy->next = head;
    while (head && head->next) {
        ListNode *nxt = head->next;
        head->next = nxt->next;
        nxt->next = head;
        node->next = nxt;
        node = head;
        head = node->next;
    }
    return dummy->next;
}

LeetCode Discussion

Memo:

Study dummy node.

Recursion need to give some implementation only once, otherwise it will be redundant.

//first version of my recursion code
//works but redundant
ListNode* swapPairs(ListNode* head) {
    if (head == NULL || head->next == NULL) return head;
    if (head->next->next == NULL) //this part is unnecessary,think why
    {
        ListNode* next = head->next;
        next->next = head;
        head->next = NULL;
        head = next;
    }
    else
    {
        ListNode* next = head->next;
        head->next = swapPairs(head->next->next); //important
        next->next = head;
        head = next;
    }
    return head;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,811评论 0 23
  • C是“面向过程”的程序设计语言;C++,C#,java是“面向对象”的程序设计语言。举个例子:比如你想做一个模型飞...
    雅然风懿阅读 867评论 1 4
  • 我的身体里有一只巨大的寄生虫。而且它越长越大,最近有疯长的趋势,隐隐的感觉我已经失去对它的控制。 最初我以为它是一...
    雏菊梦梦阅读 390评论 0 0
  • 合上《钱商》这本书,结局皆大欢喜,告诉我一个事实,诚实对待自己,尽可能公平公正的对待公众,看清事实并相信自己的...
    dreamingyou阅读 152评论 0 0