C语言-链表的各种操作
Posted 可能自洽
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C语言-链表的各种操作相关的知识,希望对你有一定的参考价值。
C语言-链表的各种操作
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct LNode* LinkList;
typedef struct LNode LinkNode;
struct LNode {
ElementType data;
LinkNode* next;
};
LinkList CreateList();
void visitNode(LinkNode* node);
int getLength(LinkList L);
void showLinkList(LinkList L);
void insertElem(LinkList L, int elem, int position);
void delteElem(LinkList L, int position);
int selectElem(LinkNode* p, int elem);
LinkNode* amendElem(LinkNode* p, int add, int newElem);
LinkNode* mergeLinkByNumOrder(LinkNode* head1, LinkNode* head2);
int main() {
LinkList L = CreateList();
showLinkList(L);
delteElem(L, 2);
showLinkList(L);
return 0;
}
LinkList CreateList() {
ElementType element;
LinkNode* head = (LinkNode*)malloc(sizeof(LinkNode));
head->next = NULL;
LinkNode* rearNode = head;
while (1) {
scanf("%d", &element);
if (element == -1) {
break;
}
else {
LinkNode* node = (LinkNode*)malloc(sizeof(LinkNode));
node->data = element;
node->next = NULL;
rearNode->next = node;
rearNode = rearNode->next;
}
}
return head;
}
void visitNode(LinkNode* node) {
printf(" %d", node->data);
}
int getLength(LinkList L) {
int length = 0;
while (L->next) {
length++;
L = L->next;
}
return length;
}
void showLinkList(LinkList L) {
int l = getLength(L);
L = L->next;
for (int i = 0; i < l; i++)
{
printf("%d ", L->data);
L = L->next;
}
}
void insertElem(LinkList L, int elem, int position) {
LinkNode* temp = L->next;
for (int i = 1; i < position; i++) {
if (temp == NULL) {
printf("插入位置无效\\n");
}
temp = temp->next;
}
LinkNode* c = (LinkNode*)malloc(sizeof(LinkNode));
c->next = NULL;
c->data = elem;
c->next = temp->next;
temp->next = c;
}
void delteElem(LinkList L, int position) {
LinkNode* temp = L->next;
for (int i = 1; i < position; i++) {
temp = temp->next;
}
LinkNode* del = temp->next;
temp->next = temp->next->next;
free(del);
}
int selectElem(LinkNode* p, int elem) {
LinkNode* t = p;
int i = 1;
while (t->next) {
t = t->next;
if (t->data == elem) {
return i;
}
i++;
}
return -1;
}
LinkNode* amendElem(LinkNode* p, int add, int newElem) {
int i = 0;
LinkNode* temp = p;
temp = temp->next;
for (i = 1; i < add; i++) {
temp = temp->next;
}
temp->data = newElem;
return p;
}
LinkNode* mergeLinkByNumOrder(LinkNode* head1, LinkNode* head2) {
LinkNode* p, * q, * r;
LinkNode* L = (LinkNode*)malloc(sizeof(LinkNode));
p = head1->next;
q = head2->next;
r = L;
while (p != NULL && q != NULL) {
if (p->data < q->data) {
r->next = p;
r = p;
p = p->next;
}
else {
r->next = q;
r = q;
q = q->next;
}
}
r->next = p ? p : q;
head1->next = NULL;
head2->next = NULL;
return L;
}
以上是关于C语言-链表的各种操作的主要内容,如果未能解决你的问题,请参考以下文章