leetcode25_k个节点一组翻转链表

 

public static ListNode reverseKGroup(ListNode head, int k) {
		ListNode dummy = new ListNode(0);
		dummy.next = head;
		ListNode current = dummy;
		while (current != null && current.next != null) {
			ListNode mostleft = current.next;
			ListNode mostright = mostleft;
			// 获取最右端节点
			int i;
			for (i = k - 1; i > 0; i--) {
				if (mostright.next == null) {
					break;
				}
				mostright = mostright.next;
			  }
			// 剩下的节点不够反转
			if (i > 0)
				break;
			ListNode next = mostright.next;
			// mostleft到mostright的反转
			ListNode innerPre = null;
			ListNode innerCur = mostleft;
			while (innerCur != next) {
				ListNode innerNext = innerCur.next;
				innerCur.next = innerPre;
				innerPre = innerCur;
				innerCur = innerNext;
			}
			current.next = mostright;
			mostleft.next = next;
			current = mostleft;

		}
		return dummy.next;
	}

 

全部评论

相关推荐

11-07 13:31
怀化学院 Java
勇敢牛牛不怕难:又疯一个
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务