美文网首页
Java循环链表的反转实现

Java循环链表的反转实现

作者: 淡泞润清田 | 来源:发表于2019-03-11 16:31 被阅读0次

    public class Node {

    public Node(int data) {
        this.data = data;
    }
    
    public int data;
    public Node next;
    
    public static Node reverse(Node head) {
        Node prev = head;
        Node cur = head.next;
        Node next = null;
        Node temp = head.next;
        while (next != temp) {
            next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
            System.out.println("翻转:cur:" + cur.data);
        }
        return cur;
    }
    

    }

    测试
    import org.junit.Test;

    public class NodeTest {
    @Test
    public void nodeReverseTest() throws Exception {

        Node head = new Node(0);
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = head;
        Node cur = head;
        System.out.println(cur.data);
        while (cur.next != head) {
            cur = cur.next;
            System.out.println(cur.data);
        }
        Node.reverse(head);
        System.out.println("翻转后:");
        System.out.println(head.data);
        cur = head;
        while (cur.next != head) {
            cur = cur.next;
            System.out.println(cur.data);
        }
    }
    

    }

    相关文章

      网友评论

          本文标题:Java循环链表的反转实现

          本文链接:https://www.haomeiwen.com/subject/fupbpqtx.html