题目描述
输入一个链表,反转链表后,输出新链表的表头。
翻转链表有两种方法,一种是再定义两个指针,另一种是递归的方法
定义两个指针的需要注意,以谁为循环的基准;对于递归的方法,深刻理解递归的内涵
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
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;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode nowNode=ReverseList(head.next);
head.next.next=head;
head.next=null;
return nowNode;
}
}