leetcode 25. Reverse Nodes in k-Group

来源:互联网 发布:买黄金投资软件 编辑:程序博客网 时间:2024/06/08 04:44

题目类型 指针操作

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode reverseKGroup(ListNode head, int k) {        if(head==null)  return head;        ListNode p = new ListNode(-1);        p.next = head;        ListNode ans = p;        ListNode[] tmp = new ListNode[k];        ListNode s=head,f=p;        for(int i=0;i<k;i++){            if(f.next!=null) f=f.next;  // f co-with tmp[i]            else{                return head;            }            tmp[i]=f;        }                while(f!=null){            p.next = f;            s.next = f.next;            p = s;  // p always before the next k nodes            s = f.next;  // renew s :tmp[0]            for(int i=k-1;i>0;i--){                tmp[i].next= tmp[i-1];            }            // the following renew f: tmp[k-1]            f = p;            if(f==null) break;            for(int i=0;i<k;i++){                if(f.next!=null) f=f.next;                else{                    f=f.next;// f==null                      break;   //break also from the out loop.                }                tmp[i]=f;            }        }        return ans.next;    }}


0 0