用java实现单链表元素的添加与删除

用java实现单链表元素的添加与删除,第1张

public class Link {

Node head = null

Node point = null

Node newNode = null

public int Count = 0//统计值

//插入

public void AddNode(int t) {

newNode = new Node()

if (head == null) {

head = newNode

} else {

point = head

while (point.next != null) {

point = point.next

}

point.next = newNode

}

point = newNode

point.vlaue = t

point.next = null

Count++

}

//返回值

public int GetValue(int i) {

if (head == null || i <0 || i >Count)

return -999999

int n

Node temp = null

point = head

for (n = 0n <= in++) {

temp = point

point = point.next

}

return temp.vlaue

}

//删除

public void DeleteNode(int i) {

if (i <0 || i >Count) {

return

}

if (i == 0) {

head = head.next

} else {

int n = 0

point = head

Node temp = point

for (n = 0n <in++) {

temp = point

point = point.next

}

temp.next = point.next

}

Count--

}

//排序

public void Sotr() {

for (Node i = headi != nulli = i.next) {

for (Node j = i.nextj != nullj = j.next) {

if (i.vlaue >j.vlaue) {

int t = i.vlaue

i.vlaue = j.vlaue

j.vlaue = t

}

}

}

}

}

class Node {

int vlaue

Node next

}

用顺序表java.util.List接口你可以选择用ArrayList或是LinkedList,前者是数组实现,后者是链表实现。例如: List list = new ArrayList()具体的相关 *** 作可以参考java提供的API文档

JDK中包含有这种类型的集合,就是Set。

如果想自己实现的话,比较繁琐,要用到内部类来实现节点,下面是一个比较粗的框架:

public class MySet

{

Node<E>first

Node<E>last

........

private class Node<T>

{

T data

Node<T>prev //指向集合中前一元素

Node<T>next //指向集合中后一元素

Node<T>(T data,Node<T>prev,Node<T>next)

{

this.data=data

this.prev=prev

this.next=next

}

}

}

哦,这是一个链表的框架,不知对你有没有帮助?


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11367691.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-15
下一篇2023-05-15

发表评论

登录后才能评论

评论列表(0条)

    保存