新手入门链表,简单写了个创建链表、插入及删除元素的程序。但是该程序还有不足:如只支持有序链表(升序或降序,降序需要对程序做简单的修改)的的插入操作;删除节点时,如果链表中有相同数值的节点,则只能删除第一个。
//必要的节点类
/*public class LinkNode {
int value;
LinkNode next;
public LinkNode() {}
public LinkNode(int value) {
this.value = value;
}
}
*/
import java.util.List;
import java.util.ArrayList;
public class LinkedList{
//定义一个指针,指向当前位置
LinkNode current;
public LinkNode createLink(int[] arr) {
int len = arr.length;
//定义头节点,数值域为-1
LinkNode head = new LinkNode(-1);
//当前指针指向头节点
current = head;
for(int i=0; i<len; i++) {
LinkNode newNode = new LinkNode(arr[i]);
current.next = newNode;
current = current.next;
}
return head;
}
//插入一个节点
public LinkNode insertNode(LinkNode head,int insert) {
LinkNode insertNode = new LinkNode(insert);
current = head;
while(current.next!=null) {
if(current.value<insert&&insert<current.next.value) {//如果当前节点的值小于插入节点的值
insertNode.next = current.next;
current.next = insertNode;
return head;
}
current = current.next;
}
//如果遍历结束还没有找到,说明插入位置在最后位,当前指针此时指向末尾
current.next = insertNode;
return head;
}
//删除指定节点
public LinkNode delete(LinkNode head,int deleteData) {
//将需要删除的数据节点化
LinkNode deleteNode = new LinkNode(deleteData);
//声明一个中间引用
LinkNode temp;
current = head;
while(current.next!=null) {
//让temp依次指向链表中的每一个节点
temp = current.next;
//比较遍历到的节点的值和需要删除的节点的值是否相等
if(temp.value == deleteNode.value) {
//相等则抛弃该节点,退出该方法
current.next = temp.next;
temp = null;
return head;
}
current = current.next;
}
return head;
}
//输出链表
public void output(LinkNode head) {
List<Integer> resultList = new ArrayList<>();
current = head;
while(current.next!=null) {
resultList.add(current.next.value);
current = current.next;
}
for(int i=0; i<resultList.size(); i++) {
if(i == resultList.size()-1) {
System.out.print(resultList.get(i));
}else {
System.out.print(resultList.get(i)+",");
}
}
}
}
输出结果
***根据数组元素创建链表*****
1,2,3,5,6
***在链表中间插入一个节点:4*****
1,2,3,4,5,6
***在链表头部插入一个节点:0*****
0,1,2,3,4,5,6
***在链表尾部插入一个节点:7*****
0,1,2,3,4,5,6,7
*****删除一个节点:7******
0,1,2,3,4,5,6
上面的程序,是升序链表的相关操作,在确定需要插入的数据的插入位置时,我使用了头节点的数值域作为判断边界,因为这个是升序链表,所以我设置头节点的数值域为负数,且越小越好,这样可以支持更广范围的数的插入。
如果更改上述程序为降序链表,需要设置头节点的数值域为正数,且越大越好。