【Leetcode25】如何K个一组反转链表

1.题目

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 list's nodes, only nodes themselves may be changed.

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Example 2:

Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Example 3:

Input: head = [1,2,3,4,5], k = 1
Output: [1,2,3,4,5]
Example 4:

Input: head = [1], k = 1
Output: [1]

2. 链表性质

/* 基本的单链表节点 */
class ListNode {
    int val;
    ListNode next;
}

void traverse(ListNode head) {
    for (ListNode p = head; p != null; p = p.next) {
        // 迭代访问 p.val
    }
}

void traverse(ListNode head) {
    // 递归访问 head.val
    traverse(head.next);
}

3.代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    
    /** 反转区间 [a, b) !!!!!的元素,注意是左闭右闭 */
    ListNode* reverse(ListNode* start,ListNode* end)
    {
     
       
        ListNode* pre;
        ListNode* cur;
        ListNode* nex;
        pre=NULL;
        cur=start;
        nex=cur;
        //这里不能判断end->next,因为可能出现空指针
        while(cur!=end)
        {
            //nex赋值必须放在最前,否则会出现NUll->NEXT情况
            nex=cur->next;
            cur->next=pre;
            cout<<cur->val<<"kkkk";
            //交换指针
            pre=cur;
            cur=nex;  
            
        }
       
        cout<<"wwwwww";
        
        //注意这里返回的是pre,因为cur已经提前交换到开区间b的位置了
       return pre;
    }
    
    ListNode* reverseKGroup(ListNode* head, int k)
    {
        
        //该题采用迭代
        ListNode *save;
        ListNode* keep=head;
        ListNode* keep2=head;
        //这里应执行k次,对应[a,b)区间
        for(int j=0;j<k;j++)
        {  
            if(keep2==NULL)
            {
                return head;
            }
            keep2=keep2->next;
          
        }
        
        save=reverse(keep,keep2);
        keep->next=reverseKGroup(keep2,k);
        return save;
        
    }
};

链接: link.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值