反转一个单链表。
如:将1->2->3->4->5反转成5->4->3->2->1。
方法一:
不断从原链表中取出结点,头插到新链表中:
1)首先需要一个新的链表;
2)遍历原链表;
3)将遍历到的结点依次头插到新链表中去。
public Node reverse(Node head){
Node result=null;
Node cur=head;
while(cur!=null){
Node next=cur.next;
cur.next=result;
result=cur;
cur=next;
}
return result;
}
方法二:
public Node reverse2(Node head){
if(head==null){
return null;
}
Node p1=null;
Node p2=head;
Node p3=head.next;
while(p2!=null){
p2.next=p1;
p1=p2;
p2=p3;
if(p3!=null){
p3=p3.next;
}
}
return p1;
}