zoukankan      html  css  js  c++  java
  • 【LeetCode】25. Reverse Nodes in k-Group

    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 nodes, only nodes itself may be changed.

    Only constant memory is allowed.

    For 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

    题意:旋转一个链表中所有相邻的K个节点

    思路:其实和旋转整个链表的思路一样,只不过多了一个递归

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     struct ListNode *next;
     6  * };
     7  */
     8 struct ListNode* reverseKGroup(struct ListNode* head, int k) {
     9     if(head==NULL) return NULL;
    10     if(1==k) return head;
    11     struct ListNode*ph=head;
    12     struct ListNode*tmp1,*tmp2,*rear,*backup;
    13     tmp1=NULL;
    14     tmp2=NULL;
    15     int i;
    16     for(i=0;i<k-1&&ph->next!=NULL;i++){
    17         ph=ph->next;
    18     }
    19     rear=ph;
    20     backup=ph->next;
    21     if(i!=k-1)
    22         return head;
    23     ph = head;
    24     i=k;
    25     while(i>0){
    26         tmp2=ph->next;
    27         ph->next=tmp1;
    28         tmp1=ph;
    29         ph=tmp2;
    30         i--;
    31     }
    32     head->next=reverseKGroup(backup,k);
    33     return rear;
    34 }
  • 相关阅读:
    shell中exec解析
    linux expr命令参数及用法详解
    Linux中变量#,#,@,0,0,1,2,2,*,$$,$?的含义
    Q_DISABLE_COPY
    lower_bound()函数
    滚动数组
    POJ 1159 Palindrome(LCS)
    C语言中short的意思
    ZOJ 2432 Greatest Common Increasing Subsequence(最长公共上升子序列+路径打印)
    ZOJ 1004 Anagrams by Stack(DFS+数据结构)
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6283427.html
Copyright © 2011-2022 走看看