Reverse a singly linked list.
A linked list can be reversed either iteratively or recursively. Could you implement both?
单链表反转
public ListNode reverseList(ListNode head) {
ListNode pre = null;
while (head != null) {
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}注意学习递归解法
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}如果输入是1->2->3->4
p=4
head=3
head.next.next = head;//4->3
head.next = null;//3不再指向4
循环下去 每次都让当前节点的下一个节点指向当前节点 让当前节点指向null 最后返回尾节点
本文介绍了两种单链表反转的方法:迭代法和递归法。通过具体的Java代码示例展示了如何实现这两种方法,并对每种方法的工作原理进行了简要说明。
769

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



