1. 题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
2. Java代码
- 法一:借助数组,遍历一次链表存入list中,在遍历一次创建链表。效率低。
public ListNode reverseList(ListNode head) {
if (head == null) return null;
List<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
ListNode p = new ListNode();
ListNode res = p;
for (int i = list.size(); i > 0; i--) {
ListNode temp = new ListNode(list.get(i-1));
p.next = temp;
p = p.next;
}
return res.next;
}
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode temp = null;
while (cur != null) {
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}