创建一个由6个结点的单向链表,实现结点的增加、删除、查找、移动、遍历显示等功能,C语言
时间: 2024-01-03 22:05:56 浏览: 78
可以通过使用结构体类型定义单向链表的节点,使用指针来串联节点,具体实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
//定义链表节点
typedef struct node {
int data;
struct node *next;
} ListNode;
//创建链表
ListNode *createList() {
ListNode *head = (ListNode*)malloc(sizeof(ListNode));
head->next = NULL;
return head;
}
//添加节点
void addNode(ListNode *head, int data) {
ListNode *newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->data = data;
newNode->next = NULL;
ListNode *p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = newNode;
}
//删除节点
int deleteNode(ListNode *head, int data) {
ListNode *p = head;
while (p->next != NULL) {
if (p->next->data == data) {
ListNode *temp = p->next;
p->next = temp->next;
free(temp);
return 1;
}
p = p->next;
}
return 0;
}
//查找节点
ListNode *findNode(ListNode *head, int data) {
ListNode *p = head->next;
while (p != NULL) {
if (p->data == data) {
return p;
}
p = p->next;
}
return NULL;
}
//移动节点
int moveNode(ListNode *head, int data, int direction) {
ListNode *p = head;
while (p->next != NULL) {
if (p->next->data == data) {
if (direction < 0 && p->next->next != NULL) {
ListNode *temp = p->next;
p->next = temp->next;
temp->next = p->next->next;
p->next->next = temp;
return 1;
} else if (direction > 0 && p->next->next != NULL) {
ListNode *temp = p->next->next;
p->next->next = temp->next;
temp->next = p->next;
p->next = temp;
return 1;
}
}
p = p->next;
}
return 0;
}
//遍历显示链表
void displayList(ListNode *head) {
ListNode *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
ListNode *head = createList();
addNode(head, 1);
addNode(head, 2);
addNode(head, 3);
addNode(head, 4);
addNode(head, 5);
addNode(head, 6);
displayList(head);
//删除节点
int deleted = deleteNode(head, 3);
if (deleted) {
printf("删除3成功\n");
} else {
printf("删除3失败\n");
}
displayList(head);
//查找节点
ListNode *node = findNode(head, 5);
if (node != NULL) {
printf("查找到5\n");
} else {
printf("未找到5\n");
}
//移动节点
int moved = moveNode(head, 2, 1);
if (moved) {
printf("将2往后移动一位成功\n");
} else {
printf("将2往后移动一位失败\n");
}
displayList(head);
return 0;
}
```
这样就可以实现一个由6个节点的单向链表,实现节点的增加、删除、查找、移动、遍历显示等功能了。
阅读全文