Java 反转单链表

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/Zhang_Zippor/article/details/50827289

反转单链表可以通过 递归遍历 两种方式实现。

首先创建一个单链表实体:

public class Node {  

    private int record;
    private Node nextNode;  

    public Node(int record) {  
        super();  
        this.record = record;  
    }  
    public int getRecord() {  
        return record;  
    }  
    public void setRecord(int record) {  
        this.record = record;  
    }  
    public Node getNextNode() {  
        return nextNode;  
    }  
    public void setNextNode(Node nextNode) {  
        this.nextNode = nextNode;  
    }  
}  



一、通过递归调用实现单链表反转:

public static Node reverseByRecursion(Node head) {  
    if (null == head || null == head.getNextNode()) {  
        return head;  
    }  
    Node reversedHead = reverseByRecursion(head.getNextNode());  
    head.getNextNode().setNextNode(head);  
    head.setNextNode(null);  
    return reversedHead;  
}



二、通过遍历链表实现单链表反转:

public static Node reverseByIterate(Node head) {  
    if (null == head) {  
        return head;  
    }  
    Node temp = head;  
    Node current = head.getNextNode();  
    Node next;  
    while (null != current) {  
        next = current.getNextNode();  
        current.setNextNode(temp);  
        temp= current;  
        current= next;  
    }      
    head.setNextNode(null);  
    head = temp;  
    return head;  
}



测试

构造单链表用于测试:

public static void main(String[] args) { 
    Node head = null;  
    Node temp = null;  
    Node current = null; 

    for (int i = 0; i < 10; i++) { 
        if (i == 0)
            head = new Node(i);
            continue;

        temp = new Node(i);  
        if (i == 1)
            head.setNextNode(temp);  
        else  
            current.setNextNode(temp);  
        current = temp;  
    }  

    Node initList = head;  // 反转前的链表  

    while (initList != null) {  // 打印
        System.out.print(initList.getRecord() + " ");  
        initList = initList.getNextNode();  
        if (initList == null)
        System.out.println("\n-------------------  ↑原始单链表,↓反转后单链表。");
    }  

    Node reverseList = reverse(head);  // 反转单链表  

    while (reverseList != null) {  // 打印
        System.out.print(reverseList.getRecord() + " ");  
        reverseList = reverseList.getNextNode();  
    }  
}



结果

0 1 2 3 4 5 6 7 8 9 
-------------------  ↑原始单链表,↓反转后单链表。
9 8 7 6 5 4 3 2 1 0 

                                               基础的扎实程度直接决定高度   - 某程序员

没有更多推荐了,返回首页