双向链表自我感觉修改的时候有点绕,不过还好,如果实在不理解一定记得画图,其实很容易,但是想出来容易漏掉一些步骤,总之就是多动手
package org.yc;
public class test {
public static void main(String[] args){
DoubleLinkedListHead head=new DoubleLinkedListHead();
head.add( new StudentNode( 1,"张三" ) );
head.add( new StudentNode( 2,"李四" ) );
head.add( new StudentNode( 3,"王五" ) );
// head.add( new StudentNode( 4,"赵六" ) );
// head.add( new StudentNode( 5,"宋七" ) );
head.addByPosition( 2,new StudentNode( 6,"王五" ) );
// head.show();
head.delete( 2 );
// head.show();
head.update( 1,new StudentNode( 7,"test" ) );
head.show();
System.out.println("*************");
head.reshow();
}
}
class DoubleLinkedListHead{
//头节点
StudentNode head=new StudentNode( 0,"头结点" );
//插入到尾部
public void add(StudentNode studentNode){
StudentNode temp=head;
while(true){
if(temp.next==null){
break;
}else{
temp=temp.next;
}
}
temp.next=studentNode;
studentNode.pre=temp;
}
//插入到指定位置
public void addByPosition(int a,StudentNode studentNode){
StudentNode temp=head;
while(a>1){
if(temp==null){
System.out.println("插入错误,指定位置大于链表长度");
}
temp=temp.next;
a--;
}
if(temp.next==null){
temp.next=studentNode;
studentNode.pre=temp;
}else{
studentNode.next=temp.next;
temp.next.pre=studentNode;
temp.next=studentNode;
studentNode.pre=temp;
}
}
//顺序输出链表
public void show(){
if(head.next==null){
System.out.println("链表为空");
return;
}else {
System.out.println( "链表顺序输出如下" );
StudentNode temp = head.next;
while (true) {
if (temp == null) {
break;
}
System.out.println( temp );
temp=temp.next;
}
}
}
//倒叙输出链表
public void reshow(){
if(head.next==null){
System.out.println("链表为空");
return;
}else {
System.out.println( "链表倒序输出如下" );
StudentNode temp = head;
while (true) {
if (temp.next == null) {
break;
}
temp=temp.next;
}
while (temp.pre!=head) {
System.out.println( temp );
temp = temp.pre;
}
System.out.println( temp );
}
}
//删除操作
public void delete(int a){
StudentNode temp=head;
while(a>1){
if(temp==null){
System.out.println("删除错误,指定位置为空");
}
temp=temp.next;
a--;
}
if(temp.next==null){
System.out.println("删除错误,指定位置为空");
}else{
temp.next=temp.next.next;
temp.next.pre=temp;
// temp.next.next.pre=temp.next; 这样写是错误的,虽然理解上没问题,但是next.next其实已经删除了
}
}
//修改操作
public void update(int a,StudentNode studentNode){
StudentNode temp=head;
while(a>1){
if(temp==null){
System.out.println("修改错误,指定位置为空");
}
temp=temp.next;
a--;
}
if(temp.next.next==null){
temp.next=studentNode;
studentNode.pre=temp;
}else{
studentNode.next=temp.next.next;
temp.next.pre=studentNode;
temp.next.next.pre=studentNode;
studentNode.pre=temp;
}
}
}
class StudentNode{
int stuNo;
String stuName;
StudentNode next;
StudentNode pre;
public StudentNode(int stuNo,String stuName){
this.stuNo=stuNo;
this.stuName=stuName;
}
@Override
public String toString() {
return "StudentNode{stuNo=" + stuNo +
", stuName=" + stuName +"}";
}
}