🚩传送门:牛客题目
题目
输入一个链表,反转链表后,输出新链表的表头。
示例 1:
输入: {1,2,3} 输出: {3,2,1}
解题思路:三指针
整理代码
public class Solution {
public ListNode ReverseList(ListNode head) {
//1. 确保头节点存在
if(head==null)return null;
//2. 初始化
ListNode RevisedHead=head; //#新的链表头节点
ListNode cur=head.next; //#cur存不存在不重要,while会判断
RevisedHead.next=null; //#链表头变链表尾巴,初始化图 1
ListNode Next=null; //#预防cur不存在
while(cur!=null){
Next=cur.next;
cur.next=RevisedHead;
RevisedHead=cur;
cur=Next;
}
return RevisedHead;
}
}