/*
链表(带头结点,c++):
1.新建链表,插入数组中的元素
2.插入指定元素在第pos位置上
3.查找指定元素
4.删除指定元素
*/
#include <cstdio>
struct node{
int in;
node *next;
};
node *create(int a[]); //新建链表
node *find(node *head, int x); //查找元素
void insert(node *head, int pos, int x); //插入元素
void delet(node *head, int x); //删除指定元素 x
void change(node *temp, int x); //修改元素 为x
void print(node *head); //输出链表
int main(){
int a[5] = {5, 3, 6, 1, 2};
node *head = create(a);
print(head);
insert(head, 3, 4); //第3个位置插入元素4
print(head);
delet(head,3);
print(head);
node *fin = find (head, 10);
change(fin, 7);
print(head);
return 0;
}
node *create(int a[]){
node *head = new node;
head->next = NULL;
node *temp, *pre = head;
for (int i = 0; i < 5; i++){
temp = new node;
temp->next = NULL;
temp->in = a[i];
pre->next = temp;
pre = temp;
}
return head;
}
void print(node *head){
node *p = head->next;
while (p != NULL){
printf("%d ", p->in);
p = p->next;
}
printf("\n");
}
void insert(node *head, int pos, int x){
node *p = head;
for (int i = 0; i < pos - 1; i++){
if (p->next != NULL){
p = p->next;
}
}
node *temp = new node;
temp->in = x;
temp->next = p->next;
p->next = temp;
}
void delet(node *head, int x){
node *pre = head, *p = head->next;
while (p != NULL && p->in != x){
pre = p;
p = p->next;
}
if (p == NULL){
printf("No Found!");
}else {
pre->next = p->next;
}
delete(p);
}
node *find(node *head, int x){
node *p = head->next;
while (p != NULL){
if (p->in != x){
p = p->next;
}else {
break;
}
}
if (p == NULL){
printf("not found\n");
return NULL;
}else {
return p;
}
}
void change(node *temp, int x){
if (temp != NULL){
temp->in =x;
}else {
printf("chang error\n");
}
}
链表增删改查
最新推荐文章于 2021-06-03 12:06:44 发布