zoukankan      html  css  js  c++  java
  • [LeetCode] 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.
    » Solve this problem

    [解题思路]
    双指针互换,要考虑一些边界条件,比如链表为空,链表长度为1,链表长度为2.
    加一个safeGuard可以避开链表长度为2的检测。

    [Code]
    1:  ListNode *swapPairs(ListNode *head) {   
    2: if(head == NULL) return NULL;
    3: if(head->next == NULL) return head;
    4: ListNode* safeG = new ListNode(-1);
    5: safeG->next= head; // head will be changed in next switch
    6: ListNode *pre = head->next;
    7: ListNode *cur = head;
    8: ListNode *post = safeG;
    9: while(pre!=NULL)
    10: {
    11: ListNode* temp = pre->next;
    12: pre->next = cur;
    13: cur->next = temp;
    14: post->next = pre;
    15: post= cur;
    16: if(post->next == NULL) break;
    17: cur = post->next;
    18: pre = cur->next;
    19: }
    20: head = safeG->next;
    21: delete safeG;
    22: return head;
    23: }

    Haoran给了一个递归解法,更简洁
    1:    ListNode *swapPairs(ListNode *head) {  
    2: if (head == NULL || head->next == NULL) {
    3: return head;
    4: }
    5: ListNode* nextPair = head->next->next;
    6: ListNode* newHead = head->next;
    7: head->next->next = head;
    8: head->next = swapPairs(nextPair);
    9: return newHead;
    10: }


  • 相关阅读:
    C# vb实现浮雕特效滤镜效果
    一张图看懂SharpImage
    C#控制操控操作多个UVC摄像头设备
    C#读写修改设置调整UVC摄像头画面-缩放
    继承多态绕点 Java篇
    继承多态绕点 C#篇
    lock关键字理解
    关于C#迭代器
    关于排列组合中组合结果
    C#与Java中相等关系
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078945.html
Copyright © 2011-2022 走看看