您的位置:首页 > Web前端 > Node.js

leetcode做题总结,题目Reverse Nodes in k-Group 2012/02/15

2014-08-19 02:46 489 查看
这道题是给一个定长,然后链表中每k个节点反转链接,比如12345,k=3,变成32145,因为要用固定的空间,所以我用的一个k大小的ListNode数组。

public ListNode reverseKGroup(ListNode head, int k) {
if(k==0||k==1)return head;
ListNode h = new ListNode(0);
h.next=head;
ListNode[] sa = new ListNode[k];
ListNode p=h,q=h;
while(true){
for(int i=0;i<k;i++){
if(q.next==null) return h.next;
sa[i]=q.next;
q=q.next;
}
q=q.next;
for(int i=k-1;i>-1;i--){
p.next=sa[i];
p=p.next;
}
p.next=q;
q=p;
}
}


Update 2015/08/23: 上面的解法又是纯属逗比,翻转链表居然放到数组里。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
private ListNode reverse(ListNode pre, ListNode end){
if(pre==null || pre.next==null)
return pre;
ListNode head = pre.next;
ListNode cur = pre.next.next;
while(cur!=end){
ListNode next = cur.next;
cur.next = pre.next;
pre.next = cur;
cur = next;
}
head.next = end;
return head;
}
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null){
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
int count = 0;
ListNode pre = dummy;
ListNode cur = head;
while(cur != null){
count ++;
ListNode next = cur.next;
if(count == k)
{
pre = reverse(pre, next);
count = 0;
}
cur = next;
}
return dummy.next;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: