题目描述
输入一个链表,反转链表后,输出新链表的表头。
包含迭代法和递归法
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null)
return null;
ListNode pre=null,next=null;
while(head!=null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
//第二种方法是构造空节点用头插法
第三种递归解法,newHead只保存头结点,链接由head完成
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;
}
}