java 链表的冒泡排序,排序之后链表的结构是已经发生变化的,可以直接根据head+temp +next节点打印全部

package interview.datastructure;


/**
  * 实现链表的插入和删除结点的操作
  */

 public class Link_list {
//定义一个结点
class Node {
    Node next = null;
    int date;
    public Node(int date) {
        this.date = date;
    }
  }
    Node head = null;

public void addNode(int d) {
    Node newNode = new Node(d);
    if (head == null) {
        head = newNode;
        return;
    }
    Node temp = head;
    //循环遍历到链表的尾部,将数据结点插入到链表的尾部
    while (temp.next != null) {
        temp = temp.next;
    }
    temp.next = newNode;
}

//删除结点
public Boolean deleteNode(int index) {
    if (index < 1 || index > length())
        return false;
    if (index == 1) {
        head = head.next;
        return true;
    }

    int i = 2;
    Node preNode = head;
    Node curNode = preNode.next;
    while (curNode != null) {
        if (i == index) {
            preNode.next = curNode.next;
            return true;
        }
        preNode = curNode;
        curNode = curNode.next;
        i++;
    }
    return true;

}

public int length() {
    int length = 0;
    Node temp = head;
    while (temp != null) {
        length++;
        temp = temp.next;
    }
    return length;
}

//冒泡排序已经改变了原来的链表的结构
public Node orderList() {
    Node nextNode = null;
    int temp = 0;
    Node curNode = head;
    while (curNode.next != null) {
        nextNode = curNode.next;
        while (nextNode != null) {
            if (curNode.date > nextNode.date) {
                temp = curNode.date;
                curNode.date = nextNode.date;
                nextNode.date = temp;
            }
            nextNode = nextNode.next;
        }
        curNode = curNode.next;
    }
    return head;
}

public void printList() {
    Node temp = head;
    while (temp != null) {
        System.out.println(temp.date);
        temp = temp.next;
    }
}

public static void main(String[] args) {
    Link_list lik = new Link_list();
    lik.addNode(3);
    lik.addNode(1);
    lik.addNode(6);
    lik.addNode(2);
    System.out.println(lik.length());
    System.out.println("排序前:");
    lik.printList();
    System.out.println("排序后:");
    lik.orderList();
    lik.printList();
}}

你可能感兴趣的:(java 链表的冒泡排序,排序之后链表的结构是已经发生变化的,可以直接根据head+temp +next节点打印全部)