关闭

【Leetcode】Reverse Nodes in k-Group

280人阅读 评论(0) 收藏 举报
分类:

题目链接:https://leetcode.com/problems/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

思路:

利用 Reverse Linked List II 中的算法,可以方便的做出来,不过时间复杂度是O(n^2)。更好的解法2 是通过本次反转起始指针往下移k,得到下次反转指针,算法复杂度为O(n)。有空会把解法2实现一下。。= =

算法:

	public ListNode reverseKGroup(ListNode head, int k) {
		int length = getListLength(head);
		for (int i = 1; (i + k - 1) <= length; i += k) {
			head = reverseBetween(head, i, i + k - 1);
		}
		return head;
	}

	public int getListLength(ListNode head) {
		int length = 0;
		ListNode p = head;
		while (p != null) {
			length++;
			p = p.next;
		}
		return length;
	}

	public ListNode reverseBetween(ListNode head, int m, int n) {
		if (head == null)
			return null;
		ListNode newHead = new ListNode(0);
		newHead.next = head;
		// start/head~rear/end,反转head到rear之间的结点,start/end是反转区间两个结点
		ListNode rear = head, start = newHead, end = head.next;
		m = m - 1;
		while (m-- > 0)// 因为start是从头结点开始算,所以要多走一步,即m--,而不是像下面的--n
			start = start.next;
		head = start.next;
		while (--n > 0)
			rear = rear.next;
		end = rear.next;
		// ===反转 head到rear之间结点
		ListNode p = head, q, t;
		q = p.next;
		while (p != rear) {
			t = q.next;
			q.next = p;
			p = q;
			q = t;
		}
		// ===
		start.next = rear;
		head.next = end;
		return newHead.next;
	}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:515521次
    • 积分:8080
    • 等级:
    • 排名:第2487名
    • 原创:305篇
    • 转载:6篇
    • 译文:0篇
    • 评论:34条
    博客专栏
    文章分类
    最新评论