简体   繁体   中英

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(1)... Am I wrong? 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. Of course, the list itself is O(n) for space complexity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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