c语言建立链式线性表,实现创建Create、显示Display、插入Insert、删除Delete、合并Merge接口函数并附上完整程序
时间: 2023-06-13 15:09:16 浏览: 76
以下是一个简单的链式线性表的完整程序,包括创建、显示、插入、删除和合并操作的接口函数:
```c
#include <stdio.h>
#include <stdlib.h>
//链表节点结构体
typedef struct node
{
int data;
struct node *next;
} Node;
//链表结构体
typedef struct linkedlist
{
Node *head;
} LinkedList;
//创建链表
void createLinkedList(LinkedList *list)
{
list->head = NULL;
}
//显示链表
void displayLinkedList(LinkedList *list)
{
Node *current = list->head;
printf("Linked List: ");
while (current != NULL)
{
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
//插入节点
void insertNode(LinkedList *list, int data, int position)
{
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (position == 1)
{
newNode->next = list->head;
list->head = newNode;
}
else
{
Node *current = list->head;
int i;
for (i = 1; i < position - 1 && current != NULL; i++)
{
current = current->next;
}
if (current == NULL)
{
printf("Invalid position!\n");
free(newNode);
return;
}
newNode->next = current->next;
current->next = newNode;
}
}
//删除节点
void deleteNode(LinkedList *list, int position)
{
if (list->head == NULL)
{
printf("Linked List is empty!\n");
return;
}
Node *current = list->head;
Node *previous = NULL;
if (position == 1)
{
list->head = current->next;
free(current);
}
else
{
int i;
for (i = 1; i < position && current != NULL; i++)
{
previous = current;
current = current->next;
}
if (current == NULL)
{
printf("Invalid position!\n");
return;
}
previous->next = current->next;
free(current);
}
}
//合并链表
void mergeLinkedList(LinkedList *list1, LinkedList *list2)
{
Node *current1 = list1->head;
while (current1->next != NULL)
{
current1 = current1->next;
}
current1->next = list2->head;
}
int main()
{
//创建两个链表
LinkedList list1, list2;
createLinkedList(&list1);
createLinkedList(&list2);
//向链表1中插入节点
insertNode(&list1, 10, 1);
insertNode(&list1, 20, 2);
insertNode(&list1, 30, 3);
insertNode(&list1, 40, 4);
insertNode(&list1, 50, 5);
//向链表2中插入节点
insertNode(&list2, 60, 1);
insertNode(&list2, 70, 2);
insertNode(&list2, 80, 3);
insertNode(&list2, 90, 4);
insertNode(&list2, 100, 5);
//显示链表1和链表2
printf("Linked List 1:\n");
displayLinkedList(&list1);
printf("Linked List 2:\n");
displayLinkedList(&list2);
//合并链表1和链表2
mergeLinkedList(&list1, &list2);
//显示合并后的链表
printf("Merged Linked List:\n");
displayLinkedList(&list1);
//删除链表1的第3个节点
deleteNode(&list1, 3);
//显示删除后的链表
printf("Linked List after deleting node at position 3:\n");
displayLinkedList(&list1);
return 0;
}
```
运行结果:
```
Linked List 1:
Linked List: 10 20 30 40 50
Linked List 2:
Linked List: 60 70 80 90 100
Merged Linked List:
Linked List: 10 20 30 40 50 60 70 80 90 100
Linked List after deleting node at position 3:
Linked List: 10 20 40 50 60 70 80 90 100
```