package com.linkedlist.exe;
/**
* @program: LinkdeList
* @Date: *****
* @Author: Kyrie
* @Description: 链表的基本操作
*/
public class Demo1_LinkedList {
private Node head; //指向头节点“指针”,其实是头节点的对象引用
private Node last; //指向尾节点“指针”,其实是尾节点的对象引用
private int size; //链表的实际节点数,与容量含义不同
public void init_list(){
/**
* @Description 初始化链表
* @Author Kyrie
* @Date 2019/5/11
* @Param []
* @Return void
*/
size = 0;
head = last;
last = null;
}
//插入节点,若链表为空则插入至头节点
public void insert(int data, int index) throws IndexOutOfBoundsException{
if(index < 0 || index > size){
throw new IndexOutOfBoundsException("索引越界异常");
}
Node new_node = new Node(data);
if(size == 0){ //
head = new_node;
last = new_node;
}else if(size == index){
last.next = new_node;
last = new_node;
}else{
//getNode(index)
Node pre_Node = getNode(index-1);
new_node.next = pre_Node.next;
pre_Node.next = new_node;
}
size++;
}
//获取指定位置的节点
public Node getNode(int index){
Node temp = head;
for (int i = 0; i < index ; i++) {
temp = temp.next;
}
return temp;
}
//遍历链表
public void printList(){
Node temp = head;
while (temp != null){
System.out.println(temp.data);
temp = temp.next;
}
}
//删除指定节点
public void deleteNode(int index){
if(index < 0 || index >= size){
throw new IndexOutOfBoundsException("越界异常");
}
Node pre_Node = getNode(index-1);
Node del_Node = getNode(index);
if(index == 0){
head = del_Node.next;
//del_Node.next = null;
}else if(index == size -1){
last = pre_Node;
pre_Node.next = null;
}else{
pre_Node.next = del_Node.next;
}
size--;
}
public static void main(String[] args) throws Exception {
Demo1_LinkedList list = new Demo1_LinkedList();
for (int i = 0; i < 5; i++) {
list.insert(12+i, i);
}
list.printList();
System.out.println("--------------------------");
list.insert(66, 3);
list.printList();
System.out.println("--------------------------");
list.deleteNode(5);
list.printList();
}
}
class Node{
public int data;
public Node next;
public Node() {
}
public Node(int data) {
this.data = data;
}
}
链表的基本操作
最新推荐文章于 2019-06-13 15:56:56 发布