单链表反转

来源:互联网 发布:哈飞里程表 算法 编辑:程序博客网 时间:2024/05/16 08:24

思路

(1)直接遍历链表,入栈,然后出栈重新构造链表
(2)递归,例如5交给4,4交给3…


代码

import java.util.*;//链表class Node {    int val;    Node next;    public Node(int val) {        this.val = val;    }}public class Main {    //递归处理后返回的头结点    static Node ans2;    //标记头结点    static Node marknode;    //1.使用栈    public static Node reverseOfList(Node pnode) {        Stack<Node> stack = new Stack<Node>();        Node temp = pnode;        while(temp != null) {            stack.push(temp);            temp = temp.next;        }        Node ans = stack.pop();        temp = ans;        while(!stack.empty()) {            temp.next = stack.pop();            temp = temp.next;        }        temp.next = null;        return ans;    }    //2.使用递归    public static Node reverseOfList2(Node pnode) {        //标记头结点,对其的next赋值null        marknode = pnode;        dfs(pnode);        return ans2;    }    public static Node dfs(Node pnode) {        Node rear;        if(pnode.next == null) {            ans2 = pnode;            rear = pnode;            return rear;        }        rear = dfs(pnode.next);        rear.next = pnode;        //如果此结点是原头结点,其next指向空        if(pnode == marknode)pnode.next = null;        return rear.next;    }    //测试    public static void main(String[] args) {        Node p = new Node(1);        p.next = new Node(2);        p.next.next = new Node(3);        p.next.next.next = new Node(4);        p.next.next.next.next = new Node(5);        Node ans = reverseOfList2(p);        Node temp = ans;        while(temp != null) {            System.out.print(temp.val+" ");            temp = temp.next;        }        System.out.println();    }}
0 0