题目描述:输入一个链表,反转链表后,输出新链表的表头。
解题思路: 有递归和非递归两种解法,注意断链问题。
解法一:非递归
public ListNode ReverseList(ListNode head) {
if(head == null) return null;
ListNode newHead = null;
ListNode pNode = head;
ListNode pPrev = null;
while(pNode != null){
ListNode pNext = pNode.next;
if(pNext == null) {
newHead = pNode;
}
pNode.next = pPrev;
pPrev = pNode;
pNode = pNext;
}
return newHead;
}
解法二:递归
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode node = ReverseList(head.next);
head.next.next = head;
head.next = null;
return node;
}