206.反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
循环代码:
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
while(cur!=null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
常用手段:
申请空节点作为前置指针:
ListNode pre = null;
申请节点保存初始头部:
ListNode cur = head;
递归解法:
class Solution {
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;
}
}