题目
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
- 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
解答
解法一:头插法
具体流程:
- 创建一个虚拟头节点,这样就不需要对头节点特殊处理了。
- 遍历原链表,将当前被遍历的结点按照头插法方式插入以虚拟头为首的链表中。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode dummy = new ListNode(0);
ListNode pre = dummy;
while(head != null) {
ListNode next = head.next;
head.next = pre.next;
pre.next = head;
head = next;
}
return dummy.next;
}
}
结果
解法二:迭代法
注意处理好 pre,p 的关系就好了。
具体可看 《剑指Offer》
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
while(head != null) {
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
结果
解法三:递归法
reverseList 方法的宏观语义:翻转 head 为头的链表,并返回新的头结点。
- 如果当前结点是 null ,或者没有下一个结点了,直接返回当前结点。
- 否则递归当前结点的 next 。
- 然后将当前结点链接到新链表的结尾。
- 最后返回新链表的头结点。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}