题目描述
解题思路
递归和遍历两种做法:
- 顺序遍历,定义 now,pre,aft 三个指针,分别指向当前节点,前一个节点,下一个节点。遍历的时候反转链表即可。让当前节点从 pre->now->next1->next2 变成 pre<-now next1->next2,pre 节点让链表反向,aft 节点记录 next1 节点,不然链表就断了。
- 递归到链表尾部,然后依次反转整个链表。细致一点的图可以看这
代码实现
import java.util.Scanner;
public class Problem15 {
public class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public static ListNode ReverseList(ListNode head) {
ListNode now = head;
ListNode pre = null;
ListNode aft = head.next;
while (now != null) {
aft = now.next;
now.next = pre;
pre = now;
now = aft;
}
return pre;
}
public static ListNode ReverseList1(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode reverseHead = ReverseList(head.next);
head.next.next = head;
head.next = null;
return reverseHead;
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
}
}