Java反转链表

package com.oracle.test;

import java.util.Stack;

import org.testng.annotations.Test;

class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }
}

public class ReverseLinkedListTest {
    
    
    ListNode reverseLinkedList(ListNode head) {
        if(head == null || head.next == null) return head;
        Stack nodes = new Stack();
        while(head!=null) {
            nodes.add(head);
            head = head.next;
        }
            

        ListNode ret = null;
        ListNode newHead = new ListNode(-1);
        
        
        
        while(!nodes.empty()) {
            ListNode tmp = nodes.pop();
            if(ret == null) {
                ret = tmp;
                newHead.next =ret;
            }else {
                ret.next = tmp;
                ret= ret.next;
                ret.next = null;
            }
        }
        
        return newHead.next;
    }
    
    
    @Test
    void testReverseLinkList() {
        ListNode [] nodes = {
                new ListNode(0),
                new ListNode(1),
                new ListNode(2),
                new ListNode(3),
                new ListNode(4),
                new ListNode(5)
        };
        
        for(int i = 0; i< nodes.length-1;i++) {
            nodes[i].next = nodes[i+1];
        }
        
        ListNode ret = reverseLinkedList(nodes[0]);
        while(ret != null) {
            System.out.println(ret.val);
            ret = ret.next;
        }
        
    }
}

输出,


Java反转链表_第1张图片
Screen Shot 2019-04-25 at 10.42.24 AM.png

你可能感兴趣的:(Java反转链表)