了解反转链表的通法:
方法一:循环
遍历一遍链表,利用一个辅助指针ne,存储遍历过程中当前指针cur指向的下一个元素,然后将当前节点元素的指针反转后,利用已经存储的指针往后面继续遍历。源代码如下:
public ListNode reverseList(ListNode head)
{
if(head==null)
return head;
ListNode pre=head;
ListNode cur=head.next;
ListNode ne=null;
while(cur!=null)
{
ne=cur.next;
cur.next=pre;
pre=cur;
cur=ne;
}
head.next=null;
head=pre;
return head;
}
方法二:递归
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null||head.next == null)
return head;
ListNode phead=ReverseList(head.next);
head.next.next=head;
head.next=null;
return phead;
}
}