面试一小时,千辛万苦来作最后做题环节,面试官准备放水,做个翻转链表吧,然后就挂了。
O(n)复杂度是不要上嵌套循环,但可以多次循环!!
遍历一次的做法
将链表分为三部分,如下
[1 ,2,3,4,5] -> [1] [2,3,4] [5],2-4是需要反转的部分,反转后和两边一连就行了。
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode root = new ListNode(-1,head);
// 链表题尽量设置虚拟的头节点,避免分类条论
ListNode thead = root;
int index = 1;// 题目中的数不是常规的index,而是从1开始的
while(index<left){
thead = thead.next;
index++;
}
// thead 指向第一部分的最后一个元素
// ttail指向当前第二部分的首元素,反转后该元素为第二部分的最后一个元素,需要标记与第三部分进行连接
ListNode ttail = thead .next, cur = thead.next,pre = null;
// 反转链表部分
while(index<=right){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
index ++;
}
// 结束后,cur 和next是同一个节点!!!都是下一个待反转的节点,还没反转!!
thead.next = pre; // 第一部分和第二部分连接
ttail.next = cur; // 第二部分和第三部分连接
return root.next;
}
}
563

被折叠的 条评论
为什么被折叠?



