时间限制:1秒 空间限制:32768K 热度指数:394494
本题知识点: 链表
题目描述
输入一个链表,反转链表后,输出新链表的表头。
1. 循环更改法
public ListNode ReverseList(ListNode head) {
if(head==null || head.next==null) return head;
ListNode pre= null, cur= head, fu= head.next;
while(cur.next!=null){
cur.next= pre;
pre= cur;
cur= fu;
fu= cur.next;
}
cur.next= pre;
return cur;
}
2. 通用方法递归法
public ListNode ReverseList(ListNode head) {
if(head== null|| head.next== null) return head;
ListNode rest= ReverseList(head.next);
head.next.next= head;
head.next= null;
return rest;
}