码迷,mamicode.com
首页 > 其他好文 > 详细

8.翻转链表

时间:2020-03-29 10:24:17      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:sel   img   alt   init   str   return   http   stack   problems   

leetcode题目位置:面试题24.反转链表

https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/

思路:借助栈的先进后出来进行反转,或者通过一个next节点来进行保存要反转到头的那个节点,防止链断裂

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode sum=new ListNode(0);
        ListNode p=head,q=sum;
        Stack<Integer> stack=new Stack();
        String a;
        while(p!=null){
            stack.push(p.val);
            p=p.next;
        }
        while(!stack.isEmpty()){
            //a=stack.pop();
            ListNode h=new ListNode(stack.pop());
            q.next=h;
            q=h;
        }
        return sum.next;
        
    }
}

技术图片

 

8.翻转链表

标签:sel   img   alt   init   str   return   http   stack   problems   

原文地址:https://www.cnblogs.com/manmanchanglu/p/12590919.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!