用C语言,创建一个链表(只包含一个int类型的链表),实现 1、创建一个空链表; 2、链表尾部添加元素; 3、链表遍历; 4、链表删除尾部元素; 5、链表修改特定元素; 6、链表查询特定元素。
时间: 2024-05-26 07:07:39 浏览: 9
当然可以,下面是实现1-6的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
Node* createList(){
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
return head;
}
void append(Node* head, int val){
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = val;
newNode->next = NULL;
Node* p = head;
while(p->next != NULL){
p = p->next;
}
p->next = newNode;
}
void traverse(Node* head){
Node* p = head->next;
while(p != NULL){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void deleteTail(Node* head){
Node* p = head;
while(p->next->next != NULL){
p = p->next;
}
free(p->next);
p->next = NULL;
}
void modify(Node* head, int pos, int val){
Node* p = head->next;
for(int i = 1; i < pos && p != NULL; i++){
p = p->next;
}
if(p != NULL){
p->data = val;
}
}
Node* search(Node* head, int val){
Node* p = head->next;
while(p != NULL){
if(p->data == val){
return p;
}
p = p->next;
}
return NULL;
}
int main(){
Node* list = createList();
append(list, 1);
append(list, 2);
append(list, 3);
traverse(list);
deleteTail(list);
traverse(list);
modify(list, 2, 4);
traverse(list);
Node* res = search(list, 2);
if(res != NULL){
printf("The position of %d is %p.\n", res->data, res);
}else{
printf("Not found.\n");
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)