题目描述
输入一个链表,反转链表后,输出新链表的表头。
解题思路:递归和非递归
//第一种方法是:非递归方法
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}*/
class Solution {
public:
public ListNode ReverseList(ListNode head) {
ListNode pre = null;
ListNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
//第二种方法是:递归方法 /*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}*/
class Solution {
public:
public ListNode reverse(ListNode head){
if(head==null || head.next==null)return head;
ListNode nodeNew=reverse(head.next);
head.next.next=head;
head.next=null;
return nodeNew;
}
};