zoukankan      html  css  js  c++  java
  • [LeetCode] Reverse Nodes in kGroup 解题报告


    Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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
    » Solve this problem

    [解题思路]
    同上一题,每K个元素,翻转一次。最后一次如果不到K,再翻转回来即可。代码中链表翻转的code可以拆分成单独函数,这里懒得再refactor了。

    [Code]
    1:      ListNode *reverseKGroup(ListNode *head, int k) {  
    2: // Start typing your C/C++ solution below
    3: // DO NOT write int main() function
    4: ListNode* safeG = new ListNode(-1);
    5: safeG->next = head;
    6: if(head == NULL || k==1) return head;
    7: ListNode* pre = safeG, *cur = head, *post = head->next;
    8: while(cur!=NULL)
    9: {
    10: post = cur->next;
    11: int i =0;
    12: while(i<k-1 && post!=NULL)
    13: {
    14: ListNode *temp = post->next;
    15: post->next = cur;
    16: cur = post;
    17: post = temp;
    18: i++;
    19: }
    20: if(i!=k-1)
    21: {
    22: int k =0;
    23: ListNode * temp = post;
    24: post = cur;
    25: cur = temp;
    26: while(k<i)
    27: {
    28: temp = post->next;
    29: post->next = cur;
    30: cur = post;
    31: post = temp;
    32: k++;
    33: }
    34: break;
    35: }
    36: ListNode* temp = pre->next;
    37: pre->next = cur;
    38: temp->next = post;
    39: pre = temp;
    40: cur = pre->next;
    41: }
    42: head = safeG->next;
    43: delete safeG;
    44: return head;
    45: }

  • 相关阅读:
    Python使用mechanize模拟浏览器
    &lt;五&gt;读《《大话设计模式》》之工厂模式
    SQLite3基本使用从shell到python
    Android Monkey具体解释
    生女孩继续生,直到男孩,100年后
    android 仿EF看视频弹出练习功能
    秒针系统-中国领先的第三方营销数据技术公司
    凤凰男_百度百科
    基于Web的在线建模工具
    WSS与Project Server集成
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078963.html
Copyright © 2011-2022 走看看