新建一个链表
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)