zoukankan      html  css  js  c++  java
  • [leetcode]算法题目

    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

    分析:

    链表操作,本身用不上什么高大上的算法或者数据结构。不过其中那些繁杂的小细节很容易搞得头大,很少能有人把这种题目一次写对吧。更可恨的是,就算写完了,隔一天在看自己之前写的思路,依然要费好多脑细胞才能理清楚。。。。。

    这道题的思路是,先计算出来链表的长度len,然后len除以k就得到我们总共需要反转几个子链表。反转链表的操作本身不难,难的在于两个子链表衔接的部分。你必须要记录清楚这个子链表的尾巴和头部,并在合适的时机设置它们指向的节点……总之很难用文字描述清楚,直接上代码吧。。就这么几行代码折腾了俩小时才搞定。

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode reverseKGroup(ListNode head, int k) {
    14         int len = 0;
    15         ListNode headbp = head;
    16         while(headbp != null){
    17             len++;
    18             headbp = headbp.next;
    19         }
    20         if(len < 2){return head;}
    21         
    22         int reverseTimes = (len / k);
    23         
    24         ListNode myhead = new ListNode(0);
    25         myhead.next = head;
    26         ListNode curr = myhead;
    27         ListNode next = head;
    28         ListNode prev = null;
    29         ListNode rhead = curr;
    30         ListNode rtail = curr.next;
    31         
    32         for(int j=0;j<reverseTimes;j++){
    33             rhead = curr; 
    34             rtail = curr.next; 
    35             curr = curr.next;             
    36             next = curr;
    37             for (int i = 0; i < k; i++) {
    38                 next = next.next;
    39                 curr.next = prev;
    40                 prev = curr;
    41                 curr = next;
    42             }
    43             rhead.next = prev;
    44             rtail.next = next;
    45             prev = null;
    46             curr = rtail;
    47         }
    48         return myhead.next;
    49     }
    50 }
  • 相关阅读:
    Codeforces Round #513解题报告(A~E)By cellur925
    Luogu P1463 [POI2002][HAOI2007]反素数【数论/dfs】By cellur925
    NOIp2016 蚯蚓 【二叉堆/答案单调性】By cellur925
    Luogu P4139 上帝与集合的正确用法【扩展欧拉定理】By cellur925
    hdu 4704 Sum【组合数学/费马小定理/大数取模】By cellur925
    poj 1723 Soldiers【中位数】By cellur925
    MyBatis 简介
    对象导航查询和OID查询(补)
    Hibernate查询方式(补)
    Hibernate一级缓存(补)
  • 原文地址:https://www.cnblogs.com/xuning/p/4430792.html
Copyright © 2011-2022 走看看