LeetCode_Reverse Nodes in k-Group

32 篇文章 0 订阅

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

分析:这道题目是“

Swap Nodes in Pairs

 ”的升级版,同时增加了链表逆序输出的功能,重点除了链表逆转之外,还要注意如果剩余的节点数小于k的话,剩余的节点就不要逆序了,剩余的节点仍按照原顺序输出,以下是Java解题代码:

public static ListNode returnNextNode(ListNode head, int k){
		//输入当前节点和k值,返回下一次循环的节点,即从当前节点向后的第k个节点,
		//若在寻找过程中链表结束,则返回输入的节点
		if(head==null)
			return head;
		ListNode current=head;
		ListNode temp = head;
		int i=0;
		while(i<k){
			temp=temp.next;
			++i;
			if(temp==null)
				return current;
		}
		return temp;
	}

	public static void reverseLink(ListNode head, int k,ListNode finish){
		//输入当前节点、k值和当前节点将要指向的节点,将该段链表逆转
		ListNode current = head;
		ListNode myNext = head.next;
		current.next=finish;
		if(k==2)
			myNext.next=current;
		else if(k>2){
			ListNode myThird = myNext.next;
			int i = 0;
			while(i+2<k&&myThird!=null){
				myNext.next=current;
				current=myNext;
				myNext=myThird;
				myThird=myThird.next;
				i++;
			}
			myNext.next=current;
		}
	}

	public static ListNode reverseKGroup(ListNode head, int k) {
		ListNode myNext=returnNextNode(head,k);
		ListNode myFinish=returnNextNode(head,k-1);
		if(head==myFinish)
			return head;
		ListNode result = myFinish;
		ListNode current=head;
		while(current!=myNext){
			myFinish = returnNextNode(myNext,k-1);
			reverseLink(current, k,myFinish);
			current=myNext;
			myNext=returnNextNode(current,k);
		}
		if(myFinish!=current){
			reverseLink(current, k,null);
		}
		return result;
	}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值