算法w13——Swap Nodes in Pairs

题目:leetcode 24.Swap Nodes in Pairs

链接:https://leetcode.com/problems/swap-nodes-in-pairs/#/description

原题:

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.

解题思路:

这题也是出于想重新拾回c++链表数据结构的原因才做的,做的时候发现指针这东西非常难,虽然题目大意简单,每两个相邻的节点互换,但实现起来关于指针的内容十分容易让人混淆。换位的第一技巧就是生成一个temp, temp = a, a=b, b=temp。在这题也一样,但唯一最重要的点是,当b=temp这一步是要将上一个节点的next指向temp的时候就有问题了,我们需要记录的存有那个next的节点,具体看代码。另外再附上一份思路效果跟我相同,但是比我简洁的代码。


代码:

/**
 * 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 || !head->next){
            return head;
        }
        ListNode* temp = head->next;
        //temp = head.next;
        head->next = head->next->next;
        temp->next = head;
        head = temp;
        
        ListNode *h = head->next;
        //ListNode *h1 = h->next;
        while(h->next && h->next->next){
            temp = h->next->next;
            h->next->next = h->next->next->next;
            temp->next = h->next;
            h->next = temp;
            h = h->next->next;
        }
        return head;
    }
};


别人简洁的代码:

ListNode* swapPairs(ListNode* head) {
    ListNode **pp = &head, *a, *b;
    while ((a = *pp) && (b = a->next)) {
        a->next = b->next;
        b->next = a;
        *pp = b;
        pp = &(a->next);
    }
    return head;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值