8.翻转链表

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;
        
    }
}

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