Leetcode(206)链表反转的三种写法

229 阅读2分钟

Reverse Linked List

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

第一种解法:迭代
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
    
    		// 单链表没有指向前一个节点的指针域,因此我们需要增加一个指向前一个节点的指针pre,
        // 用于存储每一个节点的前一个节点。此外,还需要定义一个保存当前节点的指针cur,以及下一个节点的						// next。
        // 定义好这三个指针后,遍历单链表,将当前节点的指针域指向前一个节点,之后将定义三个指针往后移动,
        // 直至遍历到最后一个节点停止

        //注意顺序的交接
        ListNode preNode = null;
        ListNode currNode = head;
        ListNode nextNode = null;
        while(currNode != null){
            nextNode = currNode.next;  //nextNode指向下一个节点
            currNode.next = preNode;   //将当前节点next域指向前一个节点
            preNode = currNode;		//preNode指针向后移动
            currNode = nextNode;	//curNode指针向后移动
        }
        return preNode;
    }
}
第二种解法:利用栈进行反转

关键点:先入栈,再出栈

public ListNode reverseList(ListNode head) {
        if (head == null){
            return null;
        }
        ListNode currNode = null;
        ListNode newNode = null;
        Stack<ListNode> left = new Stack<>();
        while (head != null){
            left.push(new ListNode(head.val));
            head = head.next;
        }
        while (left.size() != 0){
            ListNode node = left.pop();
            if (currNode == null){
                currNode = node;
                newNode = node;
                continue;
            }
            currNode.next = node;
            currNode = currNode.next;
        }

        return newNode;
    }
第三种解法:递归

这里引用官方的解法:

代码实现:

public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode p = reverseList(head.next);  //重点
        head.next.next = head;
        head.next = null;
        return p;
    }
总结

三种解法中其实利用栈来反转是最简单的,其次是迭代,最难的是递归,递归可以想成如果当前节点不是最后一个节点,就继续递归,直到最后一个,处理最后一个的场景,就是处理所有的场景。