Leetcode -- swap nodes in pairs

问题链接:https://oj.leetcode.com/problems/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.

问题API:public ListNode reverseKGroup(ListNode head, int k)

 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }


问题分析:这一题其实就是之前那一题reverse nodes in k-group 里k = 2的状态,所以利用那一题的代码就可以得到答案了,下面给出代码如下:

    public void partialReverse(ListNode head, ListNode tail){
        ListNode prev = null, next = null, tmp = head, next_group = tail.next;
        while(tmp != next_group){
            next = tmp.next;
            tmp.next = prev;
            prev = tmp;
            tmp = next;
        }
    }
    
    public ListNode reverseKGroup(ListNode head, int k) {
        int m = k - 1;
        ListNode tmp = head, prev = null, new_head = null, next = null, part_head = head, part_tail = null;
        while(tmp != null){
            m--;
            tmp = tmp.next;
            if(m == 0 && tmp != null){
                next = tmp.next;
                part_tail = tmp;
                partialReverse(part_head, part_tail);
                if(new_head == null)
                    new_head = part_tail;
                if(prev != null)
                    prev.next = part_tail;
                prev = part_head;
                part_head.next = next;
                part_head = next;
                tmp = next;
                m = k - 1;
            }
        }
        return new_head == null ? head : new_head;
    }
    
    public ListNode swapPairs(ListNode head) {
        return reverseKGroup(head, 2);
    }

当然,因为reverseKGroup需要照顾到一些泛用性,所以代码会略显冗长。下面给出来的代码会简洁很多,因为只需要处理两个指针即可,所以可以略掉一些步骤:

    public ListNode swapPairs(ListNode head) {
        if(head == null)
            return head;
        ListNode prev,next,cur,res;
        prev = null;
        cur = head;
        next = cur.next;
        res = head;
        while(cur != null && cur.next != null){
            next = cur.next;
            ListNode nextset = next.next;
            if(prev != null){
                prev.next = next;
            }else{
                res = next;
            }
            next.next = cur;
            cur.next = nextset;
            prev = cur;
            cur = nextset;
        }
        return res;
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值