建立虚拟头结点辅助反转
public ListNode reverseList(ListNode head) {
if(head == null)
return null;
ListNode dummyNode, cur, next;
dummyNode = new ListNode(-1);
cur = head;
while(cur != null)
{
next = cur.next;
cur.next = dummyNode.next;
dummyNode.next = cur;
cur = next;
}
return dummyNode.next;
}
直接操作链表实现反转
public ListNode reverseList(ListNode head) {
if(head == null)
return null;
ListNode pre, cur, next;
pre = next = null;
cur = head;
while(cur != null)
{
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
递归实现反转
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}