【每日一题】【初始节点初始化,前一个为空】2022年1月7日-NC78 反转链表
描述
给定一个单链表的头结点pHead,长度为n,反转该链表后,返回新链表的表头。
数据范围: n\leq1000n≤1000
要求:空间复杂度 O(1)O(1) ,时间复杂度 O(n)O(n) 。
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
以上转换过程如下图所示:

正确做法:
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode ReverseList(ListNode head) { if(head == null) { return null; } ListNode cur = head; ListNode pre = null; ListNode next; while(cur != null) { next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } }
其他方法:可以用递归
错误做法(把cur初始化为了第二个节点,pre初始化为了第一个节点):
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode ReverseList(ListNode head) { if(head == null) { return null; } ListNode cur = head.next; ListNode pre = head; ListNode next; while(cur != null) { next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } }
本文来自博客园,作者:哥们要飞,转载请注明原文链接:https://www.cnblogs.com/liujinhui/p/15775744.html

浙公网安备 33010602011771号