数据结构——链表的增删查改Java

``
//结点类
public class Node {
public int data;
public Node next;

public Node() {
}

public Node(int value) {
    this.data = value;
}

}

public class LinkTest {
public static void main(String[] args) {
// 创建头结点
Node head = new Node(1);

    addNode(head, 12);
    addNode(head, 20);
    addNode(head, 18);
    addNode(head, 17);
    addNode(head, 47);
    toPrintln(head);
    System.out.println("链表长度为:" + count(head));

// deleteNode(head, 2);
deleteValue(head, 20);
updateNode(head, 18, 110);
toPrintln(head);
System.out.println("链表长度为:" + count(head));
Node h = reverseList(head);
toPrintln(h);
clcyle(h);
toPrintln(h);

}

// 增加结点
public static void addNode(Node head, int value) {
    if (head == null) {
        return;
    }
    Node newNode = new Node(value);
    while (head.next != null) {
        head = head.next;
    }
    head.next = newNode;

}

// 根据位置删除结点
public static void deleteNode(Node head, int index) {
    // 插入位置不能小于0和长度大约链表长度
    if (index <= 0 && index > count(head)) {
        return;
    }
    Node cur = head;
    // 删除头结点
    if (index < 2 && index > 0) {
        cur.data = cur.next.data;
        cur.next = cur.next.next;
        return;
    }
    // 非头结点
    int j = 0;
    while (cur != null && j < index - 2) {
        cur = cur.next;
        j++;
    }
    cur.next = cur.next.next;

}

// 根据值删除结点
public static void deleteValue(Node head, int value) {
    Node current = head;
    if (current.data == value) {
        current.data = current.next.data;
        current.next = current.next.next;
        return;
    }
    while (current.next != null) {
        if (current.next.data == value) {
            current.next = current.next.next;
            break;
        }
        current = current.next;

    }

}

// 计算链表长度
public static int count(Node head) {
    Node temp = head;
    int length = 0;
    while (temp != null) {
        length++;
        temp = temp.next;
    }
    return length;
}

// 修改链表值
public static void updateNode(Node head, int oldData, int newData) {

    Node temp = head;
    while (temp != null) {
        if (temp.data == oldData) {
            temp.data = newData;
        }
        temp = temp.next;
    }
}

// 打印链表
public static void toPrintln(Node head) {
    Node temp = head;
    while (temp != null) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("value:" + temp.data);
        temp = temp.next;

    }
    System.out.println("---------------------------");
}


public static void clcyle(Node head) {
    Node temp=head;
    for(int i=0;i

}

``

你可能感兴趣的:(数据结构——链表的增删查改Java)