[Leetcode] Swap Nodes in Pairs & Reverse Nodes in k-Group

这是两道题。

24. Swap Nodes in Pairs : 把链表两两相邻的结点互换值。

25. Reverse Nodes in k-Group: 把链表中每k个结点组成的子链表翻转。

其实24就是25在k=2时候的情况。


就只讲25吧。

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


这里说,只能用常数空间,而且不能改动结点里的值。那就只能改变node的next域,用人话说就是必须把指针翻转了。206. Reverse Linked List 这道题就是翻转整个链表的,我的博客在这里


不多说了,上代码和注释。

struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
	ListNode* reverseKGroup(ListNode* head, int k) {
		if (needReverseSubList(head, k)) {
			//首先把翻转最开始的k个节点
			ListNode* nextGroupHead = head;
			ListNode* headForAll = reverseSubList(head, k, nextGroupHead);  //  headForAll是整个链表的新的头结点
			ListNode* tail = head;  //  tail记录子链表翻转后的尾节点(要和下一个子链表翻转后的头结点相连)

			while (needReverseSubList(nextGroupHead, k)) {
				head = nextGroupHead;
				ListNode* newSubHead = reverseSubList(head, k, nextGroupHead);
				tail->next = newSubHead;
				tail = head;
			}
			tail->next = nextGroupHead;
			return headForAll;
		}
		else {
			return head;
		}
	}

private:
	//  函数:判断从p开始,还够不够k个结点。够则说明需要翻转,不够则不翻转
	bool needReverseSubList(ListNode* p, int k) {
		int count = 0;
		while (p != NULL) {
			count++;
			p = p->next;
		}
		return count >= k;
	}

	//  函数:翻转从head开始的k个结点组成的子链表
	//  返回的值是这个子链表翻转后的头结点
	//  nextGroupHead参数记录了下一个子链表原本的头结点
	ListNode* reverseSubList(ListNode* head, int k, ListNode*& nextGroupHead) {
		if (head == NULL || head->next == NULL) {
			nextGroupHead = NULL;
			return head;
		}

		ListNode *p = head;
		ListNode *q = head->next;
		ListNode *r = head->next->next;
		head->next = NULL;

		int count = 0;

		while (++count < k) {
			q->next = p;
			p = q;
			q = r;
			if (r != NULL)
				r = r->next;
			else
				break;
		};

		nextGroupHead = q;
		return p;
	}
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值