翻转k个链表

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
         if(head == null || k == 1) return head;
          ListNode dummy = new ListNode(0);
          dummy.next = head;
          ListNode pre = dummy;
          int i = 0;
          while(head != null){
              i++;
              if(i % k ==0){
                 pre = reverse(pre, head.next);
                 head = pre.next;
             }else {
                 head = head.next;
            }
         }
         return dummy.next;
    }
    public static ListNode reverse(ListNode pre,ListNode next){
        ListNode last = pre.next;
        ListNode cur = last.next;
        while(cur!=next){
            last.next = cur.next;
            cur.next = pre.next;
            pre.next = cur;
            cur = last.next;
        }
        return last;
    }
}
题目描述: 给定一个链表,每k个节点为一组进行翻转。例如,给定链表1->2->3->4->5,k=2,则应返回2->1->4->3->5。请注意,你需要在不修改链表节点值的情况下完成此操作。 示例: 输入: 1->2->3->4->5, k = 2 输出: 2->1->4->3->5 思路: 这道题是链表的操作,我们可以用递归来实现,每次递归处理k个节点,翻转它们,返回翻转后的头节点,然后将它接到上一组的尾部。 具体实现: 首先,我们需要定义一个辅助函数reverse,用来翻转链表。它的实现方法是,用三个指针pre、cur、next来遍历链表,将cur的next指向pre,然后将三个指针往后移动一个节点,重复这个过程,直到遍历完整个链表。 接下来,我们可以定义一个递归函数,它的参数是链表头节点和k。如果链表的长度小于k,说明不需要翻转,直接返回头节点;否则,我们先翻转前k个节点,然后将它们的尾节点接到下一组翻转后的头节点,递归处理下一组节点。每次递归返回的是翻转后的头节点,最后将所有头节点连接起来即可。 代码实现: /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverse(ListNode* head) { ListNode* pre = NULL; ListNode* cur = head; while (cur != NULL) { ListNode* next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; } ListNode* reverseKGroup(ListNode* head, int k) { ListNode* cur = head; int cnt = 0; while (cur != NULL && cnt != k) { // 找到第k+1个节点 cur = cur->next; cnt++; } if (cnt == k) { // 如果找到了,就翻转前k个节点 cur = reverseKGroup(cur, k); // 递归处理下一组节点 while (cnt-- > 0) { // 将翻转后的头节点接到下一组节点的尾部 ListNode* next = head->next; head->next = cur; cur = head; head = next; } head = cur; } return head; } };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值