leetcode做题总结,题目Reverse Nodes in k-Group 2012/02/15

本文介绍了一种链表的处理方法,即对链表中的节点每K个进行一次反转操作。通过定义一个辅助类`Solution`及其实现方法`reverseKGroup`来完成这一功能,该方法能够高效地实现链表的局部反转。

这道题是给一个定长,然后链表中每k个节点反转链接,比如12345,k=3,变成32145,因为要用固定的空间,所以我用的一个k大小的ListNode数组。


public ListNode reverseKGroup(ListNode head, int k) {
        if(k==0||k==1)return head;
        ListNode h = new ListNode(0);
        h.next=head;
        ListNode[] sa = new ListNode[k];
        ListNode p=h,q=h;
        while(true){
        for(int i=0;i<k;i++){
            if(q.next==null) return h.next;
            sa[i]=q.next;
            q=q.next;
        }
        q=q.next;
        for(int i=k-1;i>-1;i--){
            p.next=sa[i];
            p=p.next;
        }
        p.next=q;
        q=p;
        }
    }

Update 2015/08/23: 上面的解法又是纯属逗比,翻转链表居然放到数组里。


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    private ListNode reverse(ListNode pre, ListNode end){  
        if(pre==null || pre.next==null)  
            return pre;  
        ListNode head = pre.next;  
        ListNode cur = pre.next.next;  
        while(cur!=end){  
            ListNode next = cur.next;  
            cur.next = pre.next;  
            pre.next = cur;  
            cur = next;  
        }  
        head.next = end;  
        return head;  
    }
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null){  
            return null;  
        }  
        ListNode dummy = new ListNode(0);  
        dummy.next = head;  
        int count = 0;  
        ListNode pre = dummy;  
        ListNode cur = head;  
        while(cur != null){  
            count ++;  
            ListNode next = cur.next;  
            if(count == k)  
            {  
                pre = reverse(pre, next);  
                count = 0;     
            }  
            cur = next;  
        }  
        return dummy.next;  
    }  

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值