编程实现单向链表的基本操作: 1.插入元素 2.删除元素 3.获取第i个结点的数据元素 4.判断元素是否存在 5.获取某个元素的下一个元素;C语言
时间: 2023-05-26 07:04:12 浏览: 106
c语言实现链表的基本操作,链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
// 插入元素
void insert(struct node **head, int x){
struct node *new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = x;
new_node->next = *head;
*head = new_node;
printf("Insert %d successfully.\n", x);
}
// 删除元素
void delete(struct node **head, int x){
struct node *cur = *head;
struct node *prev = NULL;
while(cur != NULL){
if(cur->data == x){
if(prev == NULL){
*head = cur->next;
} else{
prev->next = cur->next;
}
free(cur);
printf("Delete %d successfully.\n", x);
return;
}
prev = cur;
cur = cur->next;
}
printf("The element %d is not exist in the list.\n", x);
}
// 获取第i个结点的数据元素
int get(struct node *head, int index){
int i = 0;
struct node *cur = head;
while(cur != NULL){
if(i == index){
return cur->data;
}
i++;
cur = cur->next;
}
printf("The index %d is out of bounds.\n", index);
return -1;
}
// 判断元素是否存在
int has(struct node *head, int x){
struct node *cur = head;
while(cur != NULL){
if(cur->data == x){
printf("The element %d is exist in the list.\n", x);
return 1;
}
cur = cur->next;
}
printf("The element %d is not exist in the list.\n", x);
return 0;
}
// 获取某个元素的下一个元素
int getNext(struct node *head, int x){
struct node *cur = head;
while(cur != NULL){
if(cur->data == x){
if(cur->next == NULL){
printf("The element %d is the last one.\n", x);
return -1;
} else{
printf("The next element of %d is %d.\n", x, cur->next->data);
return cur->next->data;
}
}
cur = cur->next;
}
printf("The element %d is not exist in the list.\n", x);
return -1;
}
int main(){
struct node *head = NULL;
int x, index;
while(1){
printf("\nEnter the operation you want to do:\n");
printf("1. Insert an element\n");
printf("2. Delete an element\n");
printf("3. Get the i-th element\n");
printf("4. Judge whether an element exists\n");
printf("5. Get the next element of an element\n");
printf("0. Exit\n");
int op;
scanf("%d", &op);
switch(op){
case 0:
return 0;
case 1:
printf("\nEnter the element you want to insert:\n");
scanf("%d", &x);
insert(&head, x);
break;
case 2:
printf("\nEnter the element you want to delete:\n");
scanf("%d", &x);
delete(&head, x);
break;
case 3:
printf("\nEnter the index of the element you want to get:\n");
scanf("%d", &index);
x = get(head, index);
if(x != -1){
printf("The %d-th element is %d.\n", index, x);
}
break;
case 4:
printf("\nEnter the element you want to search:\n");
scanf("%d", &x);
has(head, x);
break;
case 5:
printf("\nEnter the element whose next you want to get:\n");
scanf("%d", &x);
getNext(head, x);
break;
default:
printf("\nInvalid operation.\n");
break;
}
}
return 0;
}
阅读全文