LeetCode 206. 反转链表
定义结点类
public class ListNode{
int val;
ListNode next;
}
1.前插法
1) 头指针
public ListNodereverse(ListNode head){
ListNode pre=null;
ListNode cur=head;
while(cur!=null){
ListNode tmp=cur.next;//记录下一个结点的位置
cur.next=pre;//把当前的next指向前一个
pre=cur;//将前一个指针后移到当前结点
cur=tmp;//当前结点指针后移到下一个结点
}
return pre;
}
2)头结点
public ListNodereverse(ListNode head){
ListNode head1=new ListNode();
head1.next=null;
ListNode p=head;
while(p!=null){
ListNode q=new ListNode();
q.val=p.val;
q.next=head1.next;
head1.next=q;
p=p.next;
}
return head1.next;
}
2.递归法
public ListNodereverse(ListNode head){
if(head==null||head.next==null) return head;
ListNode newhead=ListNodereverse(head.next);
head.next.next=head;
head.next=null;
return newhead;
}