206 . Reverse Linked List
Easy
Reverse a singly linked list.
0ms:
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode p = head, q=head.next, k=null;
while(q!=null){
p.next = k;
k = p;
p = q;
q = q.next;
}
p.next = k;
return p;
}
92 . Reverse Linked List II
Medium
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
0ms:
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head==null|head.next==null||m==n) return head;
ListNode previous=null,end = head,p, q,k=null;
for(int i=1;i<m;i++){
previous = end;
end = end.next;
}
p = end;
q = p.next;
while(m<=n){
p.next = k;
k = p;
p = q;
if(q!=null)
q = q.next;
m++;
}
if(previous!=null)
previous.next = k;
else
head = k;
end.next = p;
return head;
}