Reverse LinkedList两种解法

Facebook店面第一轮就挂了,先问了简历, 然后问了reverse linked list的两种解法以及分析,先用了recursive写,然后说要space O(1),写太慢了, 只写了这道题和follow up

法一:指针,时间 O(n), 空间 O(1)
由于reverse需要两个指针指向当前的reverse的两个node,因此需要两个指针,同时又需要一个指针指向后一个node来防止丢失后面的list,因此至少需要三个指针。
corner case:   1. list为空/list只有一个node:直接返回node;
		2.  list只有两个node: 可以包含在主体代码里,当第三个指针为null时结束返回。
example: 1 -> 2 -> 3 -> 4
	    1 ,  2,    3
code:
public ListNode reverseLinkedList(ListNode root) {
	if (root == null || root.next == null) return root;
	ListNode first = root;
	ListNode second = root.next;
ListNode third = root.next.next;
first.next = null;
while (third != null) {
	second.next = first;
	first = second;
	second = third;
	third = third.next;
}
second.next = first;
return second;
}
法二:递归,时间 O(n), 空间 O(n)
假设1~n-1已经全部完成,那么1 -> 2 -> 3 -> 4   ------>  3-> 2 -> 1 -> null 和 4。因此,我们就把4加在3前面即可。
corner case:和上一样
code:
public ListNode reverseLinkedList(ListNode root) {
	if (root == null || root.next == null) return root;
	ListNode cur = root;
	while (cur.next != null) {
	cur = cur.next;
}
helper(root, root.next);
return cur;
}
public void helper(ListNode first, ListNode second) {
	if (second == null) return first;
	helper(second, second.next);
	first.next = second.next;
	second.next = first;
}

猜你喜欢

转载自blog.csdn.net/katrina95/article/details/85256248
今日推荐