【算法】【线性表】【链表】反转链表

1  题目

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例 2:

示例 3:

输入:head = []
输出:[]

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000

2  解答

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: n
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {
        // write your code here
        ListNode resHead = new ListNode(head.val);
        while (head.next != null) {
            head = head.next;
            // 新建节点保存当前节点信息
            ListNode node = new ListNode(head.val);
            // 把当前节点的下一个节点指向头节点
            node.next = resHead;
            // 头节点指向当前新节点
            resHead = node;
        }
        return resHead;
    }
}

上边的空间相当于又创建了一份新的,再来个不产生新空间的头插法:

/**
 * 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 reverse(ListNode head) {
        // 参数校验
        if (head == null || head.next == null) {
            return head;
        }
        // 采用头插法进行插入
        ListNode preNode = new ListNode(0);
        preNode.next = head;

        while (head.next != null) {
            ListNode nextNode = head.next;
            head.next = nextNode.next;
            nextNode.next = preNode.next;
            preNode.next = nextNode;
        }
        return preNode.next;
    }
}

加油。

加油。

posted @ 2024-01-10 06:38  酷酷-  阅读(20)  评论(0)    收藏  举报