Reverse Linked List (E)
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?
题意
将一个链表逆向排列。
思路
普通的链表逆置方法,插入到头结点前即可。
代码实现 - 迭代
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode newHead = null;
while (head != null) {
ListNode temp = head.next;
head.next = newHead;
newHead = head;
head = temp;
}
return newHead;
}
}
代码实现 - 递归
/**
* 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 last = head.next;
ListNode newHead = reverseList(last); // 返回以last开头的链表逆置后的头结点
last.next = head;
head.next = null; // 注意要断开
return newHead;
}
}
本文详细解析了链表逆置的两种实现方式:迭代和递归。通过具体的代码示例,展示了如何将一个单向链表进行逆向排列,包括头结点的处理和链表断开等关键步骤。
424

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



