用c语言创建一个有6个结点的单向链表,实现增加、删除、查找、移动、显示结点的基本功能。
时间: 2023-12-22 09:05:37 浏览: 78
好的,这个问题是关于编程的,我可以回答。以下是使用C语言创建6个节点的单向链表的基本实现:
```
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node *next;
} Node;
// 创建节点
Node* createNode(int data) {
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 在尾部插入节点
void insertNode(Node **headRef, int data) {
Node *newNode = createNode(data);
if (*headRef == NULL) {
*headRef = newNode;
} else {
Node *lastNode = *headRef;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = newNode;
}
}
// 在指定位置插入节点
void insertNodeAtPosition(Node **headRef, int data, int position) {
Node *newNode = createNode(data);
if (position <= 1) {
newNode->next = *headRef;
*headRef = newNode;
} else {
Node *prevNode = *headRef;
for (int i = 2; i < position && prevNode != NULL; i++) {
prevNode = prevNode->next;
}
if (prevNode == NULL || prevNode->next == NULL) {
printf("Invalid position\n");
return;
}
newNode->next = prevNode->next;
prevNode->next = newNode;
}
}
// 删除节点
void deleteNode(Node **headRef, int key) {
Node *temp = *headRef, *prevNode;
if (temp != NULL && temp->data == key) {
*headRef = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != key) {
prevNode = temp;
temp = temp->next;
}
if (temp == NULL) {
printf("Node with given key not found\n");
return;
}
prevNode->next = temp->next;
free(temp);
}
// 查找节点
Node* searchNode(Node *head, int key) {
Node *temp = head;
while (temp != NULL && temp->data != key) {
temp = temp->next;
}
return temp;
}
// 移动节点
void moveNode(Node **src, Node **dest) {
Node *temp = *src;
*src = (*src)->next;
temp->next = *dest;
*dest = temp;
}
// 显示链表
void displayList(Node *head) {
Node *temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// 主函数
int main() {
Node *head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
insertNode(&head, 4);
insertNode(&head, 5);
insertNode(&head, 6);
displayList(head);
insertNodeAtPosition(&head, 7, 3);
displayList(head);
deleteNode(&head, 4);
displayList(head);
Node *foundNode = searchNode(head, 5);
printf("Found node: %d\n", foundNode->data);
Node *destNode = createNode(0);
moveNode(&head, &destNode);
displayList(head);
displayList(destNode);
return 0;
}
```
请注意,这只是一个基本实现,可能不够完善或高效。你可以根据自己的需要进行修改和改进。
阅读全文