标签:first 运行时 imp 简单 follow public 方法 根据 元素
1、Reverse Linked ListⅠ
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
1 class Solution { 2 public ListNode reverseList(ListNode head) { 3 ListNode p,q,ptr; 4 p = head; 5 q = null; 6 while( p != null ){ 7 ptr = p.next; 8 p.next = q; 9 q=p; 10 p = ptr; 11 } 12 return q; 13 } 14 }
运行时间0ms。
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
1 class Solution { 2 public ListNode reverseBetween(ListNode head, int m, int n) { 3 if ( m >= n ) return head; 4 ListNode p,q,ptr = null; 5 ListNode first0 = head,first1; 6 p = head; 7 q = null; 8 int count = 1; 9 while ( count < m ){ 10 first0 = p; 11 p = p.next; 12 count++; 13 } 14 //此时,p指针指向第一个要变动的位置,first0指针指向最后一个不变的元素。 15 first1 = p; 16 while ( count <= n ){ 17 ptr = p.next; 18 p.next = q; 19 q = p; 20 p = ptr; 21 count ++; 22 } 23 //此时完成m—n位置的翻转,然后拼接上三段 24 //注意这里分类讨论。第一种情况是全部翻转,第二种情况是从开头开始翻转到中间某个位置,第三种情况是从中间某个位置反转到最后,第四种情况是从中间某个位置到中间某个位置翻转。 25 if ( ptr == null && first0 == first1) { 26 return q; 27 } 28 if ( ptr == null ){ 29 first0.next = q; 30 return head; 31 } 32 if ( first0 == first1 ){ 33 first1.next = ptr; 34 return q; 35 } 36 first1.next = ptr; 37 first0.next = q; 38 return head; 39 } 40 }
运行时间2ms,基本上应该是最快的解法了。时间复杂度O(n),空间复杂度O(1)。
[leetcode] Reverse Linked List
标签:first 运行时 imp 简单 follow public 方法 根据 元素
原文地址:https://www.cnblogs.com/boris1221/p/9374641.html