链表的操作:1、构建空表H,插入 {"a","b",",","f"} 遍历输出单链表H 输出单链表H的长度 判断单链表H是否为空 输出单链表H的第3个元素 输出元素c的位置 在第5个位置之前插入元素e后,输出单链表 删除H的第了个元素,输出单链表H用java编程
时间: 2023-12-30 22:02:07 浏览: 55
//定义节点类
class ListNode{
String val;
ListNode next;
ListNode(String val){
this.val = val;
}
}
public class LinkedListOperations {
public static void main(String[] args) {
//构建空表H
ListNode H = new ListNode(null);
//插入 {"a","b",",","f"}
ListNode p = H;
String[] arr = {"a","b",",","f"};
for(int i = 0; i < arr.length; i++){
ListNode node = new ListNode(arr[i]);
p.next = node;
p = node;
}
//遍历输出单链表H
p = H.next;
while(p != null){
System.out.print(p.val + " ");
p = p.next;
}
System.out.println();
//输出单链表H的长度
int length = getLength(H);
System.out.println("单链表H的长度为:" + length);
//判断单链表H是否为空
boolean isEmpty = isEmpty(H);
System.out.println("单链表H是否为空:" + isEmpty);
//输出单链表H的第3个元素
String val = getVal(H, 3);
System.out.println("单链表H的第3个元素为:" + val);
//输出元素c的位置
int index = getIndex(H, "c");
System.out.println("元素c的位置为:" + index);
//在第5个位置之前插入元素e后,输出单链表
insert(H, 5, "e");
p = H.next;
while(p != null){
System.out.print(p.val + " ");
p = p.next;
}
System.out.println();
//删除H的第了个元素,输出单链表
delete(H, 1);
p = H.next;
while(p != null){
System.out.print(p.val + " ");
p = p.next;
}
}
//获取单链表长度
public static int getLength(ListNode H){
int length = 0;
ListNode p = H.next;
while(p != null){
length++;
p = p.next;
}
return length;
}
//判断单链表是否为空
public static boolean isEmpty(ListNode H){
if(H.next == null){
return true;
}else{
return false;
}
}
//获取单链表的第index个元素
public static String getVal(ListNode H, int index){
ListNode p = H.next;
int i = 1;
while(p != null && i < index){
p = p.next;
i++;
}
if(p == null || i > index){
return null;
}else{
return p.val;
}
}
//获取元素val在单链表中的位置
public static int getIndex(ListNode H, String val){
ListNode p = H.next;
int index = 1;
while(p != null){
if(p.val.equals(val)){
return index;
}
p = p.next;
index++;
}
return -1;
}
//在第index个位置之前插入元素val
public static void insert(ListNode H, int index, String val){
ListNode p = H;
int i = 1;
while(p != null && i < index){
p = p.next;
i++;
}
if(p == null || i > index){
return;
}
ListNode node = new ListNode(val);
node.next = p.next;
p.next = node;
}
//删除第index个元素
public static void delete(ListNode H, int index){
ListNode p = H;
int i = 1;
while(p != null && i < index){
p = p.next;
i++;
}
if(p == null || i > index || p.next == null){
return;
}
p.next = p.next.next;
}
}
阅读全文