package data.structure;
public class MyLinkedList<E> {
private Node head;
private class Node{
E item;
Node next;
}
public MyLinkedList(){
head = new Node();
}
public void insert(E item){
Node node = new Node();
node.item = item;
node.next = head.next;
head.next = node;
}
public int size(){
int count = 0;
Node cur = head.next;
while(cur != null){
count++;
cur = cur.next;
}
return count;
}
public boolean deleteIndexAt(int index){
if(head.next == null){
System.out.println("Delete failed, List is empty");
return false;
}
if(index > size() - 1){
System.out.println("Delete failed, index is beyond the size.");
return false;
}
Node temp = head; // record the previous node
Node deleteNode = temp.next;
for (int i = 0; i < index; i++) {
temp = temp.next;
deleteNode = deleteNode.next;
}
temp.next = deleteNode.next;
return true;
}
public void reverse(){
if(head.next == null || head.next.next == null){
return;
}
Node tempHead = new Node();
Node cur = head.next;
while (cur != null){
Node next = cur.next;
cur.next = tempHead.next;
tempHead.next = cur;
cur = next;
}
head.next = tempHead.next;
}
public void printAll(){
if(head.next == null){
System.out.println("List is empty.");
return;
}
Node cur = head.next;
while(cur != null){
System.out.println(cur.item.toString());
cur = cur.next;
}
}
public static void main(String[] args) {
MyLinkedList<Student> studentList = new MyLinkedList<>();
studentList.insert(new Student(1, "Tom"));
studentList.insert(new Student(2, "Jack"));
studentList.insert(new Student(3, "Rose"));
studentList.printAll();
studentList.reverse();
System.out.println("Print list after reversing");
studentList.printAll();
System.out.println("List size is " + studentList.size());
studentList.deleteIndexAt(2);
System.out.println("Print list after deleting the last node");
studentList.printAll();
studentList.deleteIndexAt(0);
studentList.deleteIndexAt(0);
System.out.println("Delete all nodes");
studentList.printAll();
}
}
class Student{
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
数据结构与算法(三)简单实现带头节点的LinkedList
最新推荐文章于 2022-12-07 18:33:23 发布