题目:
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.
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
Note:
- Only constant extra memory is allowed.
- You may not alter the values in the list's nodes, only nodes itself may be changed
给定一个链表,以及一个整数k,我们将链表每隔k个翻转一下,如题中举例所示
解法:
看到网上很多使用递归来做,这里我没有使用。主要遵循的逻辑如下:
对于每一段要反转的链表
我们需要两个指针 begin(begin是这段要反转的链表的前一个节点,这也是为什么要在header前新建的一个节点的原因) 和 tail
例如要反转
2 ->3-> 4
初始指针位置如下:
0 -> 2 -> 3 -> 4
| |
begin tail
这是我们操作3插入到2前面
0 -> 3 -> 2 -> 4
| |
begin tail
之后我们操作4插入到3前面
0 -> -> 4 -> 3 -> 2
| |
begin tail
反转完成后
begin=tail
tail=begin->next
开始下一段的操作
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
int n = 0; //length of list
for (ListNode *i = head; i != NULL; n++, i = i->next); //count length
ListNode *first=new ListNode(0); //add the header
first->next=head;
ListNode *pre=first;
ListNode *last=head;
for(int j=0;j<=n-k;j+=k){
for(int i=0;i<k-1;i++){
ListNode *next=last->next;
last->next=next->next;
next->next=pre->next;
pre->next=next;
}
pre=last;
last=last->next;
}
return first->next;
}
};
本文介绍了一种不使用递归的链表K个一组翻转算法,通过使用额外的begin和tail指针,实现了链表的局部翻转,同时保持了常数级别的额外内存消耗,满足题目要求。

被折叠的 条评论
为什么被折叠?



