25. Reverse Nodes in k-Group

本文介绍了一种算法,该算法能够实现链表中每K个节点为一组进行翻转的操作。通过在链表头部添加一个虚拟节点,并使用循环结构来判断并执行翻转操作,确保了链表尾部剩余节点保持原有顺序。此方法只使用常数额外内存,适用于当链表长度不是K的倍数的情况。

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;}这样会省去判断的函数。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值