1.用java实现链表结构,有增加、删除方法
注意,链表要有head;
public class MyList {
//头结点
Node head = null;
class Node {
int data;
Node next = null;
public Node(int data) {
this.data = data;
}
}
/**
* 链表尾部插入节点
*/
public void add(int d) {
Node node = new Node(d);
if(head==null) {
head = node;
return;
}
Node tmp = head;
while(tmp.next != null) {
tmp = tmp.next;
}
tmp.next = node;
}
/**
* 链表删除第index节点(从1开始)
*/
public boolean delete(int index) {
if(index<1 || index > length()) {
return false;
}
if(index == 1) {
head = head.next;
return true;
}
int i=1;
Node pre = head;
Node cur = head.next;
while(cur!=null) {
if(i == index) {
pre.next = cur.next;
return true;
}
pre = cur;
cur = cur.next;
i++;
}
return false;
}
/**
* 返回节点长度
*/
private int length() {
int length = 0;
Node tmp = head;
while(tmp.next != null) {
length ++;
tmp = tmp.next;
}
return length;
}
/**
* 在不知道头指针的情况下删除指定节点,该节点为尾节点时返回false【有点问题!】
*/
public boolean delete(Node n) {
Node node = null;
if(n.next != null) {
node = n.next;
node.data = n.next.data;
n = node;
n.data = node.data;
return true;
} else {
n = null;
return false;
}
}
}