java 实现 单链表 反转 demo

2017-07-07

41

0

技术:java8

运行环境:IDEA 15.2 + jdk8 + windows 10

demo功能:java实现单链表反转

反转代码

//每次修改新链表的头指针就好了, 这样就可以翻转
public JLinkedListStackNode reverseAndReturnHead() {
    JLinkedListStackNode tmpNewHead = null;

    JLinkedListStackNode tempOld = head;
    JLinkedListStackNode tempNew = null;

    tmpNewHead = new JLinkedListStackNode(null, tempOld.value);//新的链表
    while (tempOld.next != null) {
        tempNew = tmpNewHead;
        tmpNewHead = new JLinkedListStackNode();
        tmpNewHead.value = tempOld.next.value;
        tmpNewHead.next = tempNew;

        tempOld = tempOld.next;
    }
    return tmpNewHead;
}

测试可以自己断点看每个节点

@Test
public void testReverse() {
    JSingleLinkedList list = new JSingleLinkedList();
    list.add(10);
    list.add(11);
    list.add(13);

    JLinkedListStackNode head = list.reverseAndReturnHead();

    Assert.assertEquals(13, head.value);
}

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think