反转链表

来源:互联网 发布:c语言从右至左的运算符 编辑:程序博客网 时间:2024/04/30 04:07

这里写图片描述
最后我的解决方案还是栈:

/*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 stack = new Stack();        ListNode p = head;        while(p.next != null)        {            stack.add(p.val);            p = p.next;        }        stack.add(p.val);//最后一个节点的值        ListNode head2 = new ListNode((Integer)(stack.pop()));        ListNode p2 = head2;        while(!stack.isEmpty())        {            p2.next = new ListNode((Integer)(stack.pop()));            p2 = p2.next;        }        return head2;    }}
0 0
原创粉丝点击