1. 题目
2. 思路
(1) 迭代
- 最基本的链表操作。
(2) 递归
- 迭代方法的递归实现。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
ListNode newHead = null;
while (head != null) {
ListNode temp = head;
head = head.next;
temp.next = newHead;
newHead = temp;
}
return newHead;
}
}
class Solution1 {
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}