算法-leetcode-每日一题-实现链表反转

分析:直接上代码

public static Node reverseNode(Node x) {
    Node reversedHead = x;
    Node cur = x;      //当前链表的指针
    Node pre = null;   //用于保存上一个节点的指针
    while (cur != null) {
        Node next = cur.next;   //保存当前节点的下一个节点
        if(next == null) {//如果下一个为空,那反转结束
            reversedHead = cur;
        }
        cur.next = pre;   //将当前节点的next指向上一个节点
        pre = cur;        //当前节点就变成了上一个节点
        cur = next;       //回到正常的遍历顺序
    }
    return reversedHead;
}

猜你喜欢

转载自blog.csdn.net/wujingchangye/article/details/88593859