206. Reverse Linked List
原题链接:https://leetcode.com/problems/reverse-linked-list/description/
题目本身不难,难的是怎么写出高效优雅的代码来:
import java.util.Stack;
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
ListNode first = new ListNode(1);
ListNode second = new ListNode(2);
ListNode third = new ListNode(3);
first.next = second;
second.next = third;
ListNode tail = s.reverseList(first);
System.out.println(tail);
}
/**
* 官方方法二:递归实现,比我的要简介很多
*
* Submission Detail: beats 25.36%
* Runtime: 1 ms
*
* @param head
* @return
*/
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode tail = reverseList(head.next);
head.next.next = head;
head.next = null;
return tail;
}
/**
* 官方方法一:迭代实现,原来只需要两个指针即可,根本不需要一个栈
*
* Submission Detail: beats 100%
* Runtime: 0 ms
*
* @param head
* @return
*/
public ListNode reverseList3(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode prev = null, curr = head;
while (curr != null) {
ListNode nextNode = curr.next;
curr.next = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
// 从提交结果来看,我的两种方法效率都很差,那么就去看看官方答案吧!
/**
* 我的方法二:迭代实现
*
* Submission Detail: beats 2.93%
* Runtime: 3 ms
*
* @param head
* @return
*/
public ListNode reverseList2(ListNode head) {
if (head == null || head.next == null) {
return head;
}
Stack<ListNode> stack = new Stack<>();
while (head != null) {
stack.push(head);
head = head.next;
}
ListNode tail = stack.pop();
ListNode temp = tail;
while (!stack.empty()) {
ListNode node = stack.pop();
node.next = null;
temp.next = node;
temp = temp.next;
}
return tail;
}
/**
* 我的方法一:递归实现
*
* Submission Detail: beats 1.19%
* Runtime: 27 ms
*
* @param head
* @return
*/
public ListNode reverseList1(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode tail = reverseList(head.next);
ListNode temp = tail;
while (temp.next != null) {
temp = temp.next;
}
temp.next = head;
head.next = null;
return tail;
}
}