题目:
输入一个链表,反转链表后,输出链表的所有元素。
分析:
反转链表只需改变链接方向,改变方向时需要将原本指向后一个结点的链接方向指向前一个结点,因此需要记录下三个结点。
实现:(非递归)
public ListNode ReverseList(ListNode head) {
ListNode cur = head;
ListNode next = null;
ListNode pre = null;
if (head == null || head.next == null) {
return head;
}
while (cur != null) {
next = cur.next;
// 改变链方向
cur.next = pre;
// 移动结点,继续操作
pre = cur;
cur = next;
}
return pre;
}
实现:递归:
public ListNode Reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode secondElem = head.next;
head.next = null;
ListNode reverseRest = Reverse(secondElem);
secondElem.next = head;
return reverseRest;
}
链表反转详解
本文详细介绍了如何通过两种方法实现链表的反转:一种是非递归方法,通过改变链表节点的指向来完成反转;另一种是递归方法,通过递归调用反转剩余部分的链表并调整头部节点的指向。
172万+

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



