Sword refers to offer.24 reverse linked list (java uses the stack method to solve)

Define a function, input the head node of a linked list, reverse the linked list and output the head node of the reversed linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

answer:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
     Stack<ListNode> s=new Stack<>();
     if(head==null)
     return null;
     else{
         while(head.next!=null){
             s.push(head);
             head=head.next;
         }
         ListNode newHead=head;
         while(!s.empty()){
             head.next=s.peek();
             head=head.next;
             s.pop();
         }
         head.next=null;
         return newHead;
     }



    }
}

 

Guess you like

Origin blog.csdn.net/qq_44624536/article/details/114861304