逆序输出链表

203 阅读1分钟

题目描述

image.png

思路

  1. 需要2个变量:新链表的头结点,下一个结点(在旧链表上帮助记录head的下一个的,因为head需要在两个链表上移动)

  2. 操作

    a. 先用next结点记录此时head结点的下一个节点

    b. 记录完毕,将旧链表的头结点摘下来,接在新链表的前面

    c. 移动新链表的节点到此刻头结点的位置

    d. 讲头结点指向next结点此时的位置

代码

/**
 * 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 reverseList = null;
        // 这个节点只在旧链表上移动
        ListNode next = null;
        // 循环遍历链表
        while(head != null){
            next = head.next;
            head.next = reverseList;
            reverseList = head;
            head = next;
        }
        return reverseList;
    }
}