LeeCode 24 Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

也就是

1->2->3->4->5

2->1->4->3->5

解法一:迭代

三个指针分别指向前中后,然后进行交换

save 1
0->2
1->3
2->1
public ListNode swapPairs2(ListNode h){
        h=new ListNode(0,h);
        ListNode point=h;
        while(point!=null&&point.next!=null&&point.next.next!=null){
            point=swapFrom(point);
            point=point.next.next;
        }
        return h.next;
    }
    public ListNode swapFrom(ListNode h){
        ListNode pre=h;
        ListNode temp=h.next;
        ListNode after=h.next.next;
        pre.next=after;
        temp.next=after.next;
        after.next=temp;
        return pre;
    }

解法二:递归

(想了一会总算是推出来了)

推出来的过程

如果是一个,直接返回

如果是两个,直接交换

如果是三个,保存后面还没换的,然后换前两个,再把后面没换的换完接上

也就是

1->2->3->4->5

过程就是

1)保存2之后的链:3->4->5

2)   换1->2:其实就只要让h.next.next=h 

3)把2之后的子串换好,接上前面换好的串(有点饿呐

public ListNode swapPairs(ListNode h) {
        if(h==null||h.next==null)
            return h;

        ListNode next=h.next.next;
        ListNode first=h.next;
        h.next.next=h;
        h.next=swapPairs(next);

        return first;

    }

这里需要注意,first存在的意义是我们让1后面的串变成 3开头的串换好之后的串,1后面就不是2了,就不能直接return 1.next,我们先要把2保存起来;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值