AcWing打卡活动
《剑指Offer》打卡活动
周三第一题 反转链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*
* 思路
* 需要三个节点
* 为了防止节点断开,我们需要知道当前遍历节点的上一个节点和下一个节点
* 如下例子 三个节点不停移动
*
* 例子
* node1 node2 node3
* 将node2的next指向node1,这时,node2和node3是断开的
* 所以这时我们需要保存node3后面的节点node4
* node2 node3 node4
* 将node3指向node2,这样不断重复
*
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null) {
return null;
}
// 使用此种方法至少要保证有两个节点
if(head.next == null) {
return head;
}
// 中心节点指向头结点的下一个
ListNode hubNode = head.next;
ListNode nextNode = null;
// 左节点指向头结点
ListNode preNode = head;
preNode.next = null;
while(hubNode != null) {
// 右节点指向中心节点的下一个节点
nextNode = hubNode.next;
// 开始反转列表
hubNode.next = preNode;
if(nextNode == null) {
break;
}
// 三个节点都向后移动一位
preNode = hubNode;
hubNode = nextNode;
nextNode = nextNode.next;
}
return hubNode;
}
}