线性链表java实现_java实现线性单链表

/**

*

* 线性单链表

*/

public class LinkedLinearList {

private Node head;

private int length;// 实际长度

/**

* 初始化顺序表,长度为length

*/

public LinkedLinearList() {

length = 0;

head = new Node('0', null);

length++;

}

/**

* 将index位置赋值为c,会覆盖掉原值

*

* @param index

* @param c

*/

public void set(int index, char c) {

Node node = head;

int n = 0;

while (n 

if (node.next == null) {

node.next = new Node('0', null);

length++;

}

node = node.next;

n++;

}

if (node == null) {

node = new Node(c, null);

length++;

} else {

node.data = c;

}

}

/**

* 取得下标为index的值,如果为空返回ascii为零的字符

*

* @param index

* @param c

* @return

*/

public char get(int index) {

if (index > length - 1 || index 

System.out.println("out of size exception!");

return 0;

} else {

Node node = head;

int n = 0;

while (n 

node = node.next;

n++;

}

return node.data;

}

}

/**

* 在index位置插入c,不会覆盖掉原值

*

* @param index

* @param c

*/

public void insert(int index, char c) {

if (index 

System.out.println("out of size exception!");

return;

} else {

Node node = head;

int n = 0;

while (n 

if (node.next == null) {

node.next = new Node('0', null);

length++;

} else {

node = node.next;

}

n++;

}

if (node.next == null) {

node.next = new Node(c, null);

} else {

Node newNode = new Node(c, null);

newNode.next = node.next;

node.next = newNode;

}

length++;

}

}

/**

* 返回长度

*

* @return

*/

public int length() {

return length;

}

/**

* 删除下标为index的元素

*

* @param index

*/

public void delete(int index) {

if (index > length - 1 || index 

System.out.println("delete not exist element exception");

} else {

Node node = head;

int n = 0;

while (n 

if (node.next == null) {

node.next = new Node('0', null);

length++;

} else {

node = node.next;

}

n++;

}

node.next = node.next.next;

length--;

}

}

/**

* 查找c元素,返回第一个找的c元素的下标,没有找到返回-1

*

* @param c

*/

public int findChar(char c) {

Node node = head;

int n = 0;

while (n 

if (node.data == c)

return n;

node = node.next;

n++;

}

return -1;

}

public void show() {

Node node = head;

int n = 0;

while (n 

System.out.print(node.data + ",");

node = node.next;

n++;

}

System.out.println();

}

public static void main(String[] args) {

LinkedLinearList lll = new LinkedLinearList();

lll.set(0, 'a');

lll.set(1, 'b');

lll.set(2, 'c');

lll.set(3, 'd');

lll.set(4, 'e');

lll.show();

lll.insert(2, 'f');

lll.show();

lll.delete(2);

lll.show();

System.out.println(lll.length());

System.out.println(lll.findChar('c'));

lll.set(0, 'z');

lll.show();

}

class Node {

char data;

Node next;

public Node(char data, Node next) {

this.data = data;

this.next = next;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值