JAVA 3ms solution using Stack. first in. last out.


  • 1
    J
    public class Solution {
       public static ListNode reverseList(ListNode head) {
    		//遍历单链表入栈
    		if(head!=null){
    		Stack<ListNode> stack = new Stack<>();
    		ListNode node = head;
    		ListNode tempNode;
    		stack.push(node);
    		while (node!= null) {
    			if(node.next==null){
    				break;
    			}
    			stack.push(node.next);
    			node = node.next;
    		}
    		//栈中的数据重新组成单链表
    		tempNode = stack.pop();
    		ListNode node1 = tempNode;
    		ListNode headNew = tempNode;
    		while(node1!=head){
    			node1 = stack.peek();
    			tempNode.next = stack.pop();
    			tempNode = node1;
    		}
    		node1.next = null;
    		return headNew;
    		}else
    		return null;
    	}
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.