通过java中逻辑,实现c语言中的指针功能,文中主要含有增和删的功能,改和查比较简单,有索引就可以直接找到相关节点,然后修改相关属性。
package com.mf.link;
public class SingleLink {
Node head = null; // 头节点
class Node{
Node next;
int data;
public Node(int data){
this.data = data;
}
}
public void addNode(int d){
Node newNode = new Node(d);
if(head == null){
head = newNode;
return ;
}
Node tmp = head;
while(tmp.next != null) {
tmp = tmp.next;
}
tmp.next=newNode;
}
public boolean deleteNode(int index){
if(index < 0 || index > length()){
return false;
}
if(index == 0) {
head = head.next;
return true;
}
int i = 1;
Node preNode = head;
Node curNode = preNode.next;
while(curNode != null) {
if(i == index) {
preNode.next = curNode.next;
return true;
}
preNode = curNode;
curNode = curNode.next;
i ++;
}
return false;
}
/**
* 往链表中指定位置插入一个值
* @param index
* @param num
* @return
*/
public Node insertNode(int index, int num){
if(index < 0 || index > length()){
return null;
}
Node firstNode = new Node(num);
if(index == 0){
firstNode.next = head.next;
Node tmp = head;
head = firstNode;
firstNode = tmp;
head.next = firstNode;
return head;
}
int i = 1;
Node preNode = head;
Node curNode = head.next;
if(curNode == null){
curNode = new Node(num);
return head;
}
while(curNode != null){
if(i == index){
preNode.next = firstNode;
firstNode.next = curNode;
return head;
}
preNode = curNode;
curNode = curNode.next;
i ++;
}
return null;
}
public int length(){
int length = 0;
Node tmp = head;
while(tmp != null) {
length ++;
tmp = tmp.next;
}
return length;
}
public void printList(){
Node tmp = head;
while(tmp != null) {
System.out.print(tmp.data + " ");
tmp = tmp.next;
}
System.out.println();
}
public static void main(String[] args) {
SingleLink list = new SingleLink();
list.addNode(5);
list.addNode(2);
list.addNode(1);
list.addNode(3);
list.addNode(6);
list.addNode(9);
list.addNode(0);
System.out.println(list.length());
System.out.println("head data :" + list.head.data);
list.printList();
list.deleteNode(0); //序号从0开始
System.out.println("after:");
list.printList();
System.out.println("head data :" + list.head.data);
list.insertNode(0, 12);
list.printList();
System.out.println("head data :" + list.head.data);
list.insertNode(0, 22);
list.printList();
System.out.println("head data :" + list.head.data);
}
}