输入一个链表,反转链表后,输出链表的所有元素。

来源:互联网 发布:淘宝上传视频怎么传 编辑:程序博客网 时间:2024/05/29 02:47
思路1:遍历链表,将链表的所有元素存入一个栈中,从栈中取出元素时,依次得到的就是原链表从尾到头的节点。代码如下:
/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/import java.util.Stack;public class Solution {    public ListNode ReverseList(ListNode head) {        if(head==null){            return null;        }                Stack<ListNode> sta = new Stack<ListNode>();        while(head!=null){            sta.push(head);            head = head.next;        }                ListNode newhead = sta.pop();       //指针node        ListNode resulthead = newhead;        while(!sta.isEmpty()){            newhead.next = sta.pop();            newhead = newhead.next;        }        newhead.next = null;                return resulthead;    }}


思路2:依次遍历所有节点,将所有节点的next指向前一个节点,代码如下:

/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/public class Solution {    public ListNode ReverseList(ListNode head) {        ListNode pre = null;        ListNode next = null;                while(head!=null){            next = head.next;          //持有下一个节点的引用            head.next = pre;           //将当前节点对下一个节点的引用指向前一个节点            pre = head;                //将前一个节点指向当前节点            head = next;               //将当前节点指向下一个节点        }        return pre;    }    }

0 0