面试题16. 反转链表

xiaoxiao2021-02-28  102

题目描述 输入一个链表,反转链表后,输出链表的所有元素。

思路: 设置三个指针,表示前、中、后。

注意特殊输入 链表为null的情况 只有一个节点的情况

/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode ReverseList(ListNode head) { ListNode pre = null, next = null; while(head != null) { next = head.next; head.next = pre; pre = head; head = next; } return pre; } }
转载请注明原文地址: https://www.6miu.com/read-63343.html

最新回复(0)