题目描述:
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
一:迭代
建议看B站课程:
https://www.bilibili.com/video/BV1iB4y1P7PU?p=1
//方法一:迭代
public static ListNode reverseList1(ListNode head) {
ListNode pre=null,curr=head,next;
while(curr!=null){
next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}
二:递归
https://www.bilibili.com/video/BV1iB4y1P7PU?p=2
//方法二:递归
public static ListNode reverseList2(ListNode head) {
if(head==null || head.next==null) {//访问到最后一个元素时就直接返回该节点
return head;
}
ListNode new_head = reverseList2(head.next);//从尾结点返回时是 new_head={val=5, next=null}
//head={val=4, next={val=5, next=null}}
head.next.next=head;
head.next=null;
return new_head;//经过head.next.next=head;head.next=null;之后 new_head={val=5, next={val=4, next=null}}
}
递归里面一定要注意的是什么呢,就是出口,以及最末尾的 return new_head,我注释了在元素为4的这个节点返回的结果便于去理解为什么是 new_head 。
我在这里懵逼了接近一个小时,所以最后一定要记录下来。递归算法就是我的黑洞!
测试用的完整代码
package jianzhiOffer;
public class ReverseList24 {
//方法一:迭代
public static ListNode reverseList1(ListNode head) {
ListNode pre=null,curr=head,next;
while(curr!=null){
next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}
//方法二:递归
public static ListNode reverseList2(ListNode head) {
if(head==null || head.next==null) {//访问到最后一个元素时就直接返回该节点
return head;
}
ListNode follow = reverseList2(head.next);//从尾结点返回时是follow={val=5, next=null}
//head={val=4, next={val=5, next=null}}
head.next.next=head;
head.next=null;
return follow;//经过head.next.next=head;head.next=null;之后follow={val=5, next={val=4, next=null}}
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1, null);
ListNode node2 = new ListNode(2, null);
ListNode node3 = new ListNode(3, null);
ListNode node4 = new ListNode(4, null);
ListNode node5 = new ListNode(5, null);
node1.next=node2;
node2.next=node3;
node3.next=node4;
node4.next=node5;
node5.next=null;
System.out.println(reverseList2(node1));
System.out.println("============================");
node1.next=node2;
node2.next=node3;
node3.next=node4;
node4.next=node5;
node5.next=null;
System.out.println(reverseList1(node1));
}
}