您的位置:首页 > 编程语言 > Java开发

java 链表操作,删除尾结点,指定位置结点

2018-01-17 12:30 274 查看
这两天随便看了看 java 的链表,发现了一些有意思的事情。

一个单向连边一般只有一个头结点,头结点的结点指向,然后是链表的大小了。

若要对其他结点进行操作,必须对链表进行遍历,找到这个结点,然后进行相关操作。

遍历的代码一般是:

for (Node x = first; x != null; x = x.next){
// 处理 x.item;
}


链表的相关操作:

1. 添加新的头结点

2. 删除尾结点

3. 删除指定位置结点

4. 在指定位置添加结点

5. 查找链表里是否含有某个值

我自己编写的一个单向链表如下:

/**
* @author chen zhen
* @version 创建时间:2018年1月17日 上午10:56:50
* @value 类说明: 链表的一些操作
*/
public class MyLink {
private Node first; // 一个头结点
private int N;            // 链表长度

public MyLink() {
first = null;
N = 0;
}

/**
* 自定义一个节点类
*/
public static class Node{
int item;
Node next;
}

// 链表表头添加一个新的结点
public void addNode(int i) {
Node temp = first;
first = new Node();
first.item = i;
first.next = temp;
N++;
}

// 删除一个尾结点
public void deleteLastNode() {
if (N == 0)
return;
if (N == 1)
first = null;
else
for (Node x = first; x != null; x = x.next) {
if (x.next.next == null)
x.next = null;
}
N--;
}

// 删除指定位置的结点
public void deletePosition(int position) {
if (position  == 1) {
first = null;
return;
}
if (position > N)
System.out.println("the position is too large");
else {
int index = 1; // 记录遍历的位置
for (Node x = first; x != null; x = x.next) {
if (index + 1 == position) {
x.next = x.next.next;
break;
}
index++;
}
}
}

//在指定位置添加结点
public void addToPosition(int position, int value) {
if (position > N + 1)
System.out.println("the position is too large");
else {
int index = 1;
for (Node x = first; x != null; x = x.next) {
if (index + 1 == position) {
Node temp = new Node();
temp.item = value;
temp.next = x.next;
x.next = temp;
break;
}
index++;
}
}
}

// 查找链表里是否含有某个值
public boolean find(int key) {
for (Node x = first; x != null; x = x.next) {
if (x.item == key)
return true;
}
return false;
}

// 定义一个 toString,方便打印
public String toString() {
StringBuilder str = new StringBuilder();
for (Node x = first; x != null; x = x.next) {
str.append(x.item);
str.append(" ");
}
return str.toString();
}

public static void main(String[] args) {
MyLink link = new MyLink();
link.addNode(1);
link.addNode(2);
link.addNode(3);
link.addNode(4);

System.out.println(link.toString());

link.deleteLastNode();
System.out.println(link.toString());

link.deletePosition(2);
System.out.println(link.toString());

link.addToPosition(2, 10);
System.out.println(link.toString());

System.out.println(link.find(2));
}

}


输出结果:

4 3 2 1

4 3 2

4 2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐