数据结构学习——链表结构

储存结构定义:

struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
struct Node{
    ElemType Element;
    Position Next;
};

代码书写:

package theDataStructureAboutLinked;

/**
 * 该类用于充当连表节点
 */
public class Node {

	// 存储的数据
	public String data;
	// 下一个节点
	public Node nextNode;
	// 当这个节点是节点头时
	static public Node head = new Node();
	public  Node() {
		
	}
	// 构造方法——存储数值
	public  Node(String data) {
		this.data = data;
	}

	// 计算该链表的长度
	public int length() {
		int length = 0;
		Node temp = head;
		while (temp.nextNode != null) {
			length++;
			temp = temp.nextNode;
		}
		return length;
	}

	// 添加节点
	public void addNode(Node data) {
		Node temp = head;
		while (temp.nextNode != null) {
			temp = temp.nextNode;
		}
		temp.nextNode = data;
	}

	// 插入节点
	public void insertNode(int index, Node data) {
		// 首先判断传入参数是否有误
		if (index < 1 || index > length()) {
			return;
		}
		Node temp = head;
		int length = 0;
		// 找到相对应下标数值
		while (temp.nextNode != null) {
			if (index == length++) {
				data.nextNode = temp.nextNode;
				temp.nextNode = data;
				return;
			}
			temp = temp.nextNode;
		}
	}

	// 删除节点
	public void deleteNode(int index) {
		// 首先判断传入参数是否有误
		if (index < 1 || index > length()) {
			return;
		}
		// 设置开头值
		Node temp = head;
		// 设置长度
		int length = 0;
		// 找到该下标点
		while (temp.nextNode != null) {
			if (index == length++) {
				temp.nextNode = temp.nextNode.nextNode;
				return;
			}
			temp = temp.nextNode;
		}
	}

	// 打印
	public void show() {
		Node a = head.nextNode;
		while (a != null) {
			System.out.println(a.data);
			a = a.nextNode;
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值