206. 反转链表
题目:反转一个单链表。
进阶:
链表可以迭代或递归地反转。你能否两个都实现一遍?
非递归代码:
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null) return null;
ListNode pre = null, nex = null;
while(head != null){
nex = head.next;
head.next = pre;
pre = head;
head = nex;
}
return pre;
}
}
递归代码:
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next ==null)
return head;
ListNode prev = reverseList(head.next);
head.next.next = head;
head.next = null;
return prev;
}
}