Leetcode 206 反转链表 (链表)

Leetcode 206 反转链表 (链表)

    • 新建一个链表
    • 解法1
    • 解法2

Leetcode 206 反转链表 (链表)_第1张图片

新建一个链表

public class ListNode(){
	int val;
	ListNode next;
	public ListNode(){}
	public ListNode(int val){this val = val;}
	public ListNode(int val, ListNode next){this val = val; this next = next;}
}

解法1

时间复杂度O(N)
空间复杂度O(1)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null) return head;
        ListNode dummyhead = new ListNode(0);
        ListNode right;
        int i = 0;
        while(head != null){

            right = head.next;
            head.next = dummyhead;
            while(i==0){
                head.next = null;
                i++;
            }
            dummyhead = head;
            head = right;
        }
        return dummyhead;
    }
}
   

解法2

时间复杂度O(N)
空间复杂度O(N)




你可能感兴趣的:(Leetcode,leetcode,链表,算法,java)