Reverse Linked List
程序员文章站
2022-01-15 12:00:10
...
#记录经典问题,方便以后复习。
题目:
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
1、非递归
public static ListNode reverseList1(ListNode head) {
ListNode prev = null; //当前节点的前一个节点
ListNode curr = head; //当前节点
while (curr != null) {
ListNode nextTemp = curr.next; //当前节点的下一个节点
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev; //当前节点指向了null,所以返回当前节点的上一个节点
}
2、递归
public static ListNode reverseList2(ListNode head) {
if (head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
推荐阅读
-
Oracle Rman 命令详解(List report backup configure)
-
Python多层嵌套list的递归处理方法(推荐)
-
C - Write the program expr which evaluates a reverse Polish expression from the command line
-
Mybatis如何从数据库中获取数据存为List类型(存为model)
-
list对象去重
-
Python中字典(dict)和列表(list)的排序方法实例
-
unknown column field list解决方案
-
Python-嵌套列表list的全面解析
-
递归一个List
,可自己根据需要改造为通用型。 -
ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains