leetcode:25. Reverse Nodes in k-Group

来源:互联网 发布:淘宝静物拍摄怎么做 编辑:程序博客网 时间:2024/06/07 23:16

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

Subscribe to see which companies asked this question


我的思路:将链表拆成k个链表,每个链表两个元素之间在原链表的距离为k,然后利用归并的思想将这k个链表归并,归并的顺序为拆开的逆序。例如当链表为1 2 3 4 5 6 7 8 9,k为3时,三个链表分别为1 4 7,2 5 8,3 6 9;归并的顺序为3 2 1 6 5 4 9 8 7。思路不麻烦,实现起来也不容易。

代码如下:

    //利用k路归并的思想    public ListNode reverseKGroup(ListNode head, int k) {    if(k==1){    return head;    }            if(!canAssign(head,k)){            return head;        }        ListNode[] kRoad = new ListNode[k];     //保存k个子链表的头结点        ListNode[] kLast = new ListNode[k];     //保存k个子链表的尾节点        ListNode p = head;        for(int i=0;i<k;i++){                   //初始化子链表            kRoad[i] = p;            kLast[i] = p;            p = p.next;        }        while(canAssign(p,k)){             for(int i=0;i<k;i++){               //拆链,更新尾节点                kLast[i].next = p;                kLast[i] = p;                p = p.next;                     //注意,这里p保存了最后不满k个节点的剩余节点            }        }        for(int i=0;i<k;i++){                  //将k个子链的最后节点置为null。            kLast[i].next = null;        }        ListNode lastNode = new ListNode(1);   //执行归并操作,lastNode保存已经连起来的最后一个节点        ListNode preHead = lastNode;        ListNode firstList = kRoad[k-1];       //这个节点只用来标识循环结束        while (firstList!=null){            firstList = firstList.next;            for(int i=k-1;i>=0;i--){                lastNode.next = kRoad[i];                lastNode = kRoad[i];                kRoad[i] = kRoad[i].next;      //更新kRoad链表,已经保存的就不需要了            }                    }        while (p!=null){            lastNode.next = p;            lastNode = p;            p = p.next;        }        return preHead.next;    }    //检查是否还有至少k个节点    public boolean canAssign(ListNode p,int k){        int i=0;        while(i<=k && p!=null){            p = p.next;            i++;        }        if(i<k){            return false;        }        return true;    }

  

0 0
原创粉丝点击