头指针单链表
public class LinkedList {
Node head;
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.addAtRear(2);
linkedList.addAtFront(1);
linkedList.showAll();
linkedList.del(2);
linkedList.showAll();
}
public void showAll() {
if (isEmpty()) {
System.out.println("链表为空");
}
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
public int del(int data) {
if (isEmpty()) {
throw new RuntimeException("链表为空");
}
if(head.data == data)
{
head = head.next;
return 1;
}
Node current = head;
while(current.next != null ) {
if(current.next.data == data) {
current.next = current.next.next;
return 1;
}
current = current.next;
}
return -1;
}
public void addAtFront(int data) {
Node node = new Node(data);
if (isEmpty()) {
head = node;
return ;
}
node.next = head;
head = node;
}
public void addAtRear(int data) {
Node node = new Node(data);
if(isEmpty()) {
head = node;
return ;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = node;
}
public boolean isEmpty() {
return head == null;
}
}
class Node{
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
头指针双向循环链表
public class DoubleLinkedList {
public static void main(String[] args) {
DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
doubleLinkedList.addAtFront(1);
doubleLinkedList.addAtFront(2);
doubleLinkedList.showAll();
}
DoubleNode head;
public void showAll() {
if (isEmpty()) {
System.out.println("链表为空");
}
System.out.println(head.data);
DoubleNode current = head.next;
while (current != head) {
System.out.println(current.data);
current = current.next;
}
}
public int del(int data) {
if (isEmpty())
throw new RuntimeException("链表为空");
if (head.data == data) {
DoubleNode next = head.next;
head.pre.next = head.next;
head.next.pre = head.pre;
head = next;
return 1;
}
DoubleNode current = head;
while (current.next != head) {
if (current.data == data) {
current.pre.next = current.next;
current.next.pre = head.pre;
return 1;
}
current = current.next;
}
return -1;
}
public void addAtFront(int data) {
DoubleNode node = new DoubleNode(data);
if (isEmpty()) {
head = node;
return;
}
DoubleNode current = head;
while (current.next != head) {
current = current.next;
}
node.next = head;
head.pre = node;
current.next = node;
node.pre = current;
head = node;
}
public boolean isEmpty() {
return head == null;
}
public DoubleNode getHead() {
return head;
}
}
class DoubleNode {
int data;
DoubleNode pre;
DoubleNode next;
public DoubleNode(int data) {
this.data = data;
this.pre = this;
this.next = this;
}
}