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;
}
}
本文详细介绍了如何通过迭代和递归方法反转单链表。包括使用空节点作为前置指针、保存初始头部节点等关键步骤,并附带了完整的代码实现。
201

被折叠的 条评论
为什么被折叠?



