第24题:原地逆置单链表

欢迎转载,转载请务必注明出处:http://blog.csdn.net/alading2009/article/details/46592801
github:https://github.com/frank-cq/MyTest

第24题:原地逆置单链表

ps:这题是当年数据结构课上的一个课后习题,当时用的就是原地逆置。


代码

package test024;

import common.CommonFunctions;
import common.Node;

import java.util.LinkedList;

/**
 * Created by cq on 2015/6/22.
 * 第24题:原地单链表逆置
 */
public class Test024 {
    //原地逆置单链表
    public static Node inverseLinkedList(Node linkedList){
        if (Node.getLength(linkedList) < 2){
            return linkedList;
        }

        Node previous = null;
        Node next = linkedList.getNext();
        linkedList.setNext(previous);

        while (next != null){
            previous = linkedList;
            linkedList = next;
            next = next.getNext();

            linkedList.setNext(previous);
        }

        return linkedList;
    }

    public static void main(String[] args){
        Node linkedList = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        linkedList.setNext(node2);
        node2.setNext(node3);
        node3.setNext(node4);
        node4.setNext(node5);

        System.out.print("逆置前单链表为:");
        CommonFunctions.printList(linkedList);
        linkedList = inverseLinkedList(linkedList);
        System.out.print("逆置后单链表为:");
        CommonFunctions.printList(linkedList);
    }
}
    //打印链表
    public static void printList(Node list){
        while (list != null){
            System.out.print(list.getData()+" ");
            list = list.getNext();
        }
        System.out.println();
    }
package common;

/**
 * Created by cq on 2015/6/22.
 */
public class Node {
    private int data;
    private Node next;
    public Node(int data){
        this.data = data;
        this.next = null;
    }
    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    public static int getLength(Node list){
        int len = 0;
        while (list != null){
            len++;
            list = list.getNext();
        }
        return len;
    }
}




执行结果

Connected to the target VM, address: '127.0.0.1:43879', transport: 'socket'
逆置前单链表为:1 2 3 4 5 
逆置后单链表为:5 4 3 2 1 
Disconnected from the target VM, address: '127.0.0.1:43879', transport: 'socket'

Process finished with exit code 0
原文地址:https://www.cnblogs.com/read-the-spring-and-autumn-annals-in-night/p/12041971.html