🚩传送门:牛客题目

题目

输入一个链表,反转链表后,输出新链表的表头。

示例 1:

输入: {1,2,3} 输出: {3,2,1}

解题思路:三指针

image.png
image.png
image.png
image.png
image.png

整理代码

  1. public class Solution {
  2. public ListNode ReverseList(ListNode head) {
  3. //1. 确保头节点存在
  4. if(head==null)return null;
  5. //2. 初始化
  6. ListNode RevisedHead=head; //#新的链表头节点
  7. ListNode cur=head.next; //#cur存不存在不重要,while会判断
  8. RevisedHead.next=null; //#链表头变链表尾巴,初始化图 1
  9. ListNode Next=null; //#预防cur不存在
  10. while(cur!=null){
  11. Next=cur.next;
  12. cur.next=RevisedHead;
  13. RevisedHead=cur;
  14. cur=Next;
  15. }
  16. return RevisedHead;
  17. }
  18. }