题目描述
输入一个链表,反转链表后,输出新链表的表头。
迭代
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode res = null;
ListNode cur = head;
ListNode pre = null;
while(cur != null) {
ListNode next = cur.next;
if(next == null) {
res = cur;
}
cur.next = pre;
pre = cur;
cur = next;
}
return res;
}
}
递归
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode newHead = ReverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}