链表类
public class Node{
int data;
Node next;
public Node(int data){
this.data = data;
}
}
1.插入元素创建链表
当一个链表的最后一个节点的next为null时即为链表的末尾节点,现在末尾节点后继续添加节点,先将新节点放在最后,然后修改上一个末尾节点的next。
public void add(int data){
Node node = new Node(data);
if(head==null){
head = node;
}else{
last.next = node;
}
last = node;
}
2.在指定位置插入节点
先找到要插入的位置的前一节点,并将前一节点的next指向新节点,新节点的next则指向前一节点之前的next
public void insert(int location,int data){
Node node = head;
int i = 0;
while(node!=null&&i<location-2){
node = node.next;
i++;
}
Node newnode = new Node(data);
newnode.next = node.next;
node.next = newnode;
}
3.删除指定位置的节点
类似于插入指定节点,先找出要删除的节点位置的前一节点,将next改为next的next
public void delete(int location){
Node node = head;
int i=0;
while(node!=null&&i<location-2){
node = node.next;
i++;
}
node.next = node.next.next;
}
4.修改节点数据
找出该节点位置,修改数值即可
public void modify(int location,int data){
Node node = head;
int i=0;
while(node!=null&&i<location-1){
node = node.next;
i++;
}
node.data = data;
}
5.打印链表
public void print(){
Node node = head;
while(node!=null){
System.out.print(node.data);
node = node.next;
}
}
6.链表长度
public int length(){
int length = 0;
Node node = head;
while(node!=null){
length++;
node = node.next;
}
return length;
}
7.查找指定位置节点
public Node get(int location){
Node node=head;
int i=1;
while(node!=null&&i<location){
node=node.next;
i++;
}
return node;
}
完整测试
public class javatest {
Node head =null;
Node last =null;
public class Node{
int data;
Node next;
public Node(int data){
this.data = data;
}
}
public void add(int data){
Node node = new Node(data);
if(head==null){
head = node;
}else{
last.next = node;
}
last = node;
}
public void insert(int location,int data){
Node node = head;
int i = 0;
while(node!=null&&i<location-2){
node = node.next;
i++;
}
Node newnode = new Node(data);
newnode.next = node.next;
node.next = newnode;
}
public void delete(int location){
Node node = head;
int i=0;
while(node!=null&&i<location-2){
node = node.next;
i++;
}
node.next = node.next.next;
}
public void modify(int location,int data){
Node node = head;
int i=0;
while(node!=null&&i<location-1){
node = node.next;
i++;
}
node.data = data;
}
public void print(){
Node node = head;
while(node!=null){
System.out.print(node.data);
node = node.next;
}
}
public int length(){
int length = 0;
Node node = head;
while(node!=null){
length++;
node = node.next;
}
return length;
}
public static void main(String[] args){
javatest link = new javatest();
link.add(1);
link.add(2);
link.add(3);
link.add(4);
link.add(5);
link.add(6);
link.add(7);
link.add(8);
link.add(9);
link.add(10);
System.out.println(link.length());
System.out.println("head.data:" + link.head.data);
link.print();
System.out.println();
link.modify(1, 888);
System.out.println("after modipfy:" );
link.print();
System.out.println();
link.delete(6);
System.out.println("after delete:" );
link.print();
}
}
输出结果:
10
head.data:1
12345678910
after modipfy:
8882345678910
after delete:
888234578910