内部类实现链表的增加、删除、插入、倒置

最经复习数据结构,自己实现了个链表倒置。

/*
* @author Danny Bai e-mail:dannybai7@gmail.com
* @2009-10-26
*/
package com.bintree;

public class Link {
/* 内部类开始 */
class Node {
private String name;
private Node next;

public Node(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
//添加节点
public void addNode(Node newNode) {
if (this.next == null) {
this.next = newNode;
} else {
this.next.addNode(newNode);
}
}
//输出节点
public void printNode() {
System.out.println(this.name);
if (this.next != null) {
this.next.printNode();
}
}
//搜索节点
public boolean serachNode(String name) {
if (name.equals(this.name)) {
return true;
} else {
if (this.next != null) {
return this.next.serachNode(name);
} else {
return false;
}
}
}
//删除节点
public void deleteNode(Node preNode, String name) {
if (name.equals(this.name)) {
preNode.next = this.next;
} else {
this.next.deleteNode(preNode, name);
}
}
//插入节点
//在名为position的节点前插入新节点
public void insertNode(Node preNode, Node newNode, String position) {
if (name.equals(this.name)) {
preNode.next = newNode;
newNode.next = this;
} else {
this.next.insertNode(preNode, newNode, name);
}
}
//倒置节点
public void reverseNode(Node preNode) {
if (this.next != null) {
Node tempNode = this.next;//存放下一个节点,用于递归调用
this.next = preNode;
tempNode.reverseNode(this);
} else {//最后一个节点,递归结束
this.next = preNode;
head = this;//将倒置后的根节点传给外部类的head变量,用于打印输出
}
}
}
/* 内部类结束 */

private Node root;

private Node head;//链表倒置时存放倒置后的根节点

public void add(String name) {
Node newNode = new Node(name);
if (this.root == null) {
this.root = newNode;
} else {
this.root.addNode(newNode);
}
}

public void print() {
if (this.root != null) {
this.root.printNode();
}
}

public boolean serach(String name) {
if (this.root != null) {
return this.root.serachNode(name);
} else {
return false;
}
}

public void delete(String name) {
if (this.serach(name)) {
if (name.equals(this.root.name)) {//删除根节点
if (this.root.next != null) {
this.root = this.root.next;
} else {
this.root = null;
}
} else {
this.root.next.deleteNode(root, name);
}
} else {
System.out.println("不存在名为 " + name + " 的节点");
}
}

public void insert(String position, String name) {
if (this.serach(position)) {
Node newNode = new Node(name);
if (position.equals(this.root.name)) {
newNode.next = this.root;
this.root = newNode;
} else {
this.root.next.insertNode(root, newNode, position);
}
}
}

public void reverse() {
if (this.root.next != null) {
this.root.next.reverseNode(root);
this.root.next = null;
this.root = head;
}

}
}

class Test {
public static void main(String[] args) {
Link link = new Link();
link.add("1");
link.add("2");
link.add("3");
link.add("4");

link.reverse();
link.print();

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值