链表反转
给定单链表的头节点 head ,请反转链表,并返回反转后的链表的头节点。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
递归方法实现
提示:head.next.next=head; head.next=null;
public static ListNode reverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}else{
ListNode listNext=reverseList ( head.next);
head.next.next=head;
head.next=null;
return listNext;
}
}
迭代方法实现
提示:这里可以添加要学的内容
public static ListNode reverseList1(ListNode head){
ListNode prev=null,next;
ListNode curr=head;
while(curr!=null ){
next=curr.next;
curr.next=prev;
prev=curr;
curr=next;
}
return prev;
}