剑指 Offer II 024. 反转链表

剑指 Offer II 024. 反转链表,第1张

剑指 Offer II 024. 反转链表

题目:给定单链表的头节点 head ,请反转链表,并返回反转后的链表的头节点。

示例:

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

解题:用指针n1存住下一节点,另头节点指向另一指针n2,让指针n2等于头节点,头节点再等于n1,进行下一次循环。

public class ListNode {

    int val;
    ListNode next;

    public ListNode(int Date) {
        this.val = Date;
        this.next = null;
    }

    ListNode() {
    }

    public ListNode getNext() {
        return next;
    }

    @Override
    public String toString() {
        return val + "->" + getNext();
    }
}
 public static void main(String[] args) {
        int[] arr = {3, 5, 7, 9};
        ListNode head = new ListNode();
        ListNode temp = head;
        for (int i = 0; i < arr.length; i++) {
            ListNode temp1 = new ListNode(arr[i]);
            temp.next = temp1;
            temp = temp1;
        }
        System.out.println(head);
        System.out.print(reverseList(head));

    }

    public static ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode n1 = null;
        ListNode n2 = null;
        while (head != null) {
            n1 = head.next;          //暂存下面节点
            head.next = n2;          //头指针指n2
            n2 = head;               //头指针赋值给n2
            head = n1;               //头指针指向下一个
        }
        return n2;
    }

输出结果:

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5707238.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存