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.
方法1:在链表前加一个头结点,while循环,每次判断后面有没有k个节点,存在就传入前面节点指针和k,并将这一段内的节点倒置过来,返回最后一个节点指针。(倒置单链表,两个指针指向当前两个节点,一个temp指针指向下一个节点)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* determinePre(ListNode* pre, int k){
if(pre==NULL) return NULL;
ListNode* pre1=pre;
while(k>0&&pre1->next){
pre1=pre1->next;
k--;
}
if(k==0) return pre1;
else return NULL;
}
ListNode* reverseList(ListNode *pre,int k){
ListNode *returnvalue= pre->next;
ListNode *pre1=pre->next;
ListNode *pre2=pre1->next;
ListNode *temp;
while(k-1>0){
temp=pre2->next;
pre2->next=pre1;
pre1=pre2;
pre2=temp;
k--;
}
pre->next->next=temp;
pre->next=pre1;
return returnvalue;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode *newhead = new ListNode(0);
newhead->next= head;
ListNode *pre=newhead;
if(head==NULL||head->next==NULL||k==1) return head;
while(determinePre(pre,k)){
pre=reverseList(pre,k);
}
return newhead->next;
}
};注:参考别人的代码,发现可以先计算链表的总长度m,while(m>=k) {转置;m-=k;}这样会省去判断的函数。
本文介绍了一种算法,该算法能够实现链表中每K个节点为一组进行翻转的操作。通过在链表头部添加一个虚拟节点,并使用循环结构来判断并执行翻转操作,确保了链表尾部剩余节点保持原有顺序。此方法只使用常数额外内存,适用于当链表长度不是K的倍数的情况。
446

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



