给出reverse List的方法 以及 使用快慢指针法得到List的后半段List的方法的代码:
public class ReverseListNode {
public ListNode reverse(ListNode head){
ListNode prev=null,nextNode=null;
while(head!=null){
nextNode=head.next;
head.next=prev;
prev=head;
head=nextNode;
}
return prev;
}
public ListNode getMidhalf(ListNode head){
ListNode slow=head,fast=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
if(fast!=null)
slow=slow.next;
return slow;
}
public ListNode generateList(int[]l){
ListNode head,p;
head=new ListNode(l[0]);
p=head;
for(int i=1;i<l.length;i++){
p.next=new ListNode(l[i]);
p=p.next;
}
p.next=null;
return head;
}
public static void main(String[]args){
ReverseListNode c=new ReverseListNode();
int[]list={1,2,3,4,5,6};
ListNode head=c.generateList(list);
// head=c.reverse(head);
head=c.getMidhalf(head);
while(head!=null){
System.out.print(head.val+" ");
head=head.next;
}
}
}