反转链表

包括三个版本,递归、栈、以及算法版 

package com.test;

import java.util.Stack;

public class ReverseList {
    public static void reverse(Node head) {
        if (head.next == null || head == null) {// 局部变量表内容越多,栈帧越大,栈深度越小。
            return;
        }
        reverse(head.next);
        head.next.next = head;
        head.next = null;
    }

    public static void reverseNonRecursive(Node head) {
        if (head.next == null || head == null) {//如果都不够两个就终止
            return;
        }
        Stack<Node> stack = new Stack<>();
        while (head != null) {
            stack.push(head);
            head = head.next;
        }
        Node temp_1 = stack.pop();//存储出来的那个
        while (!stack.empty()) {
            Node temp_2 = stack.pop();
            temp_1.next = temp_2;
            temp_2.next = null;
            temp_1 = temp_2;
        }
    }

    public static void reverse2(Node head) {//直接遍历
        if (head.next == null || head == null) {//如果都不够两个就终止
            return;
        }
        Node pre = head;
        Node cur = head.next;
        while (cur.next != null) {//调整的是pre 和 cur之间的 方向, 跳出之后最后一次别忘调整
            Node temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        head.next  =null;//最初的head也没调整
        cur.next = pre;
    }

    public static void main(String[] args) {
        Node a = new Node(1);
        Node b = new Node(2);
        Node c = new Node(3);
        a.next = b;
        b.next = c;
        reverseNonRecursive(a);
        System.out.println("finished");
    }
}

class Node {
    int value;
    Node next = null;

    Node(int value) {
        this.value = value;
    }
}

另附剑指offer版本

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null){
            return null;
        }
        if(head.next == null){
            return head;
        }
        ListNode pre = null;
        ListNode next = null;//关键点,需要保存next
        while (head != null){
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值