简体   繁体   English

反向单链表

[英]Reverse single linked list

I was implementing the "reverse single linked list, do it in-place" task.我正在实施“反向单链表,就地执行”任务。 I came up with this solution:我想出了这个解决方案:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }

        if(head.next==null) return head;

        ListNode n = head;
        ListNode r = null;
        ListNode temp = null;

        while (n != null) {
            temp = n;
            n = n.next;
            temp.next = r;
            r = temp;
        }

        return r;
    }
}

and it works:它有效:

1 2 3 4 5 
5 4 3 2 1 

but when I wanted to make sure it's the right approach all the solutions I've seen online look like that Reverse single linked list so I started questioning myself... What is wrong with my solution?但是当我想确保它是正确的方法时,我在网上看到的所有解决方案看起来都像反向单链表,所以我开始质疑自己......我的解决方案有什么问题? Time complexity looks like O(n) space com.时间复杂度看起来像 O(n) 空间 com。 O(1)... Am I wrong? O(1)...我错了吗? Thanks in advance!提前致谢!

Not sure what you are asking.不确定你在问什么。 Your implementation looks almost just like the one in the link.您的实现与链接中的实现几乎一模一样。 Both implementations are O(n) for time complexity, and O(1) for space complexity.两种实现的时间复杂度均为O(n) O(1) ,空间复杂度为O(1) Of course, the list itself is O(n) for space complexity.当然,列表本身的空间复杂度是O(n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM