题目详述
反转一个链表
解法一
迭代。需要两个临时指针一个指向前驱一个指向后继
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while(curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
}
解法二
递归。
class Solution {
public ListNode reverseList(ListNode head) {
//若只有一个节点,可防止其出现循环
if(head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
}