206翻转链表
翻转链表
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
思路:直接看代码吧
1、迭代法
class Solution {
public ListNode reverseList(ListNode head) {
ListNode p = head;
ListNode pre = null;
ListNode q ;
while(p != null){
q = p.next;
p.next = pre;
pre = p;//前驱指针后移
p = q;//当前指针后移
}
return pre;
}
2、递归法
只考虑两个节点,前驱和当前。
递归不要忘了退出条件!!
class Solution {
public ListNode reverseList(ListNode head) {
return reverse(null,head);
}
public Static ListNode reverse(ListNode pre,ListNode cur){
if(cur == null) return pre;
ListNode q = cur.next;
cur.next = pre;
return reverse(cur,q)
}
}