LeetCode_OJ【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.

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

此题难度为hard,虽然思路很常见,但是能一次性不出错地写出来确实不太容易(可怜我WA了好多次 T_T)。这种题目还是很能考察一个人基本功的。

对于每次要操作的K个元素,记录这K个元素的第一个为start,最后一个元素为end,start前面的元素为pre,首先处理start和pre元素,处理start的时候要记录start.next,否则链表就断掉了,后面的直接丢失了,然后处理start至end之间的所有节点。

具体代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(k < 2){
            return head;
        }
		ListNode dummy = new ListNode(-1);
		dummy.next = head;
		ListNode pre = dummy, end = dummy;
		while(end != null){
			for(int i = 0 ; i < k && end != null ; i++ ){
				end = end.next;
			}
			if(end == null){
				break;
			}
			ListNode start = pre.next;
			pre.next = end;
			pre = start;
			ListNode cur = start.next;               //要处理start节点则需要保存start.next节点
			start.next = end.next;
			while(cur != end){
				ListNode after = cur.next;       //要处理cur节点则需保存cur.next节点
				cur.next = start;
				start = cur;
				cur = after;
				after = after.next;
			}
			end.next = start;
			end = pre;
		}
        return dummy.next;
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值