题目描述
反转链表
思路
和leetcode的206. Reverse Linked List一样
迭代:
- 记录当前结点的下一个结点
- 反转指针
- 继续下一个结点
- 返回反转后的头结点
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null) return null;
// 反转后的头结点
ListNode newHead = null;
while (head != null) {
// 记录当前结点的下一个结点
ListNode next_node = head.next;
// 反转指针
head.next = newHead;
newHead = head;
// 继续下一个结点
head = next_node;
}
return newHead;
}
}
递归:
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode head_next = head.next;
head.next = null;
ListNode newHead = ReverseList(head_next);
head_next.next = head;
return newHead;
}
}

本文详细介绍了如何通过迭代和递归两种方式实现链表的反转。迭代方法通过记录当前节点的下一个节点,反转指针并继续到下一个节点来完成反转过程;递归方法则通过递归调用自身来反转链表的剩余部分。
140

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



