Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
//java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode result = reverseList(head.next);
head.next.next = head;
head.next = null;
return result;
}
}
本文深入解析了链表的反转算法,提供了迭代和递归两种实现方式,并附带Java代码示例。通过具体实例,展示了输入链表从1->2->3->4->5->NULL反转为5->4->3->2->1->NULL的过程。
333

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



