淘先锋技术网

首页 1 2 3 4 5 6 7

1、栈方法实现

将链表遍历入栈,再通过出栈形成一个新的链表,根据栈的特性可以完整链表的反转。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
// 1 - 2 - 3 - 4 - 5 - null
// 5 - 4 - 3 - 2 - 1 - null
class Solution {
    public ListNode reverseList(ListNode head) {
        // 创建一个空栈
        Stack<ListNode> stack = new Stack<>();
        // 设置一个空的节点,当做是链表的末尾 null 
        ListNode start = new ListNode(0,new ListNode(0));
        // 临时变量用于形成反转后的链表
        ListNode temp = start;
        // 入栈
        while(head!=null){
            stack.push(head);
            head = head.next;
        }
        // 出栈
        while(!stack.isEmpty()){
            temp.next = stack.pop();
            temp = temp.next;
        }
        temp.next = null;
        return start.next;
        
    }
}

2、双指针迭代

设置两个指针,pre指针指向head前一个节点,cur指向head。

每次移动都将 cur指针指向pre,pre移动到cur,cur移动到cur.next,,直到移动到 末尾 null

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while(cur!=null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
        
    }
}

3、递归(理解加强)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head ==null || head.next == null){
            return head;
        }
        // 层层调用,直到末尾
        ListNode cur = reverseList(head.next);
        // 将 head 后面的 节点 指向 head
        head.next.next = head;
        // 防止链表循环
        head.next = null;
        return cur;
    }
}