输入一个链表,反转链表后,输出新链表的表头。
思路
还是递归好想
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;
}
}
迭代,你指针赋值之前一定要保存下一个指针在哪,不然会找不到
class Solution {
public ListNode ReverseList(ListNode head) {
if (head==null || head.next==null) return head;
ListNode pre=null, post=head;
while (head!=null) {
post=head.next;
head.next=pre;
pre=head;
head=post;
}
return pre;
}
}
原文:https://www.cnblogs.com/wdt1/p/13846418.html