LeetCode 25. Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

链表局部翻转的题,不能new新链表。

由于每次只反转k个,链表长n,那么可以每次处理k个,最后处理一下尾部即可。

reverseK2用来每次处理k个,这里用了递归,不需要new对象。


在调用reverseK2时,还是要先遍历链表,移动k次,找到尾部及每次剩余链表的头。


在做完reverseK2后,要将处理后的尾部与剩余链表首部相连,这里比较容易错,试了几次才写对

 

 public ListNode reverseKGroup(ListNode head, int k) {
      if(head==null||head.next==null||k<2)return head;
    	
    	int count=1;
    	ListNode cur=head;
    	while(count<k&& cur!=null){//先看有没有k个
    			cur=cur.next;
    			count++;
    		
    			
    	}
    	if(count<k||cur==null)return head;
    	ListNode newHead=cur.next;
    	reverseK2(head,k);
    	ListNode lastTail = head;
    	head = cur;
    	if(newHead==null){
    		//这里还要处理一下tail
    		lastTail.next=null;
    		return head;
    		
    		}
    	while(1==1){
    		count=1;
    		cur=newHead;
    		while(count<k){//先看有没有k个
        		if(cur!=null){
        			cur=cur.next;
        			count++;
        		}
        		else{
        			lastTail.next=newHead;
        			return head;
        		}
        	}
    		if(count<k||cur==null){
    			lastTail.next=newHead;
    			return head;
    		}
    		ListNode temp=newHead;
    		newHead=cur.next;
        	reverseK2(temp,k);
        	lastTail.next=cur;
        	lastTail = temp;
    		
    	}
        
    }
    public static ListNode reverseK2(ListNode head, int k) {
    	if(head==null||head.next==null||k<2)return head;
    	 reverseK2(head.next,k-1);
    	 head.next.next=head;
    	 return head;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值