Closed PisecesPeng closed 2 years ago
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public static ListNode func(ListNode head) {
if (head == null) return null;
ListNode point = new ListNode(0);
reverse(head, point);
return point.next;
}
public static ListNode reverse(ListNode listNode, ListNode point) {
ListNode val = new ListNode(listNode.val);
ListNode tmp;
// 一旦递归到链表末尾, 就开始回溯构造链表
if (listNode.next != null)
tmp = reverse(listNode.next, point);
else
tmp = point;
tmp.next = val;
return tmp.next;
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode func(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = func(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode func(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
反转链表
示例:
进阶 :
你可以迭代或递归地反转链表.你能否用两种方法解决这道题?
题目地址: https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/