(链表)01-反转链表

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode ReverseList(ListNode head) {
12         // 申请临时变量
13         ListNode current = head;
14         ListNode pre = null;
15         // 依次调换指针的方向
16         while (current != null) {
17             // 记录下个要处理的节点
18             ListNode next = current.next;
19             // 调换当前节点的指针方向
20             current.next = pre;
21             // 移动到下个要处理的节点
22             pre = current;
23             current = next;
24         }
25         // 返回调换后的头节点
26         return pre;
27     }
28 }

 

posted @ 2023-11-13 22:47  StringBuilder  阅读(15)  评论(0)    收藏  举报