反转链表
2026年3月25日小于 1 分钟
反转链表
使用的方法
- 无
解题思路
思路就是原地调换链表的指针。
- 初始化三个指针:
current指向当前节点,before指向前一个节点,nextList指向下一个节点。 - 在迭代过程中,首先保存当前节点的下一个节点(
nextList = current.next) - 然后将当前节点的
next指针指向前一个节点(current.next = before)。 - 接着将
before指针移动到当前节点(before = current),并将current指针移动到下一个节点(current = nextList)。 - 当
current指针为null时,说明已经遍历完链表,此时before指针指向新的头节点,返回before即可。
代码实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode current = head;
ListNode before = null;
ListNode nextList = null;
while(current != null){
nextList = current.next;
current.next = before;
before = current;
current = nextList;
}
return before;
}
}