本篇是用C语言来实现,数据结构中的链式存储及其基础操作。
- 链表
其结构体成员:内容info,下一个节点的指针。
C代码实现如下
#include <stdio.h>
typedef int DataType;
struct node
{
DataType info;
struct node *next;
};
typedef struct node *Node;
//创建空链表
Node CreateNULLlink()
{
Node head=(Node )malloc(sizeof(struct node));
if(head!=NULL)
{
head->info=0;
head->next=NULL;
return head;
}
return NULL;
}
//判断链表是否为空
int IsNULLlink(Node head)
{
return (head->next==NULL);
}
//输出链表
void Printlink(Node head)
{
Node temp=head->next;
while(temp!=NULL)
{
printf("%d ", temp->info);
temp=temp->next;
}
printf("\n");
}
//带头节点的尾插法
int InsertLink(Node head, DataType x)
{
Node p, temp=(Node )malloc(sizeof(struct node));
if(head==NULL || temp==NULL) return 0;
p=head->next;
temp->info=x;
temp->next=NULL;
if(p==NULL)
{
head->next=temp;
return 1; //记得返回值
}
while(p->next!=NULL)
{
p=p->next;
}
p->next=temp;
return 1;
}
//头插法
int InsertPre(Node head, DataType x)
{
Node p, temp=(Node )malloc(sizeof(struct node));
if(temp==NULL) return 0;
temp->info=x;
temp->next=head->next;
head->next=temp;
return 1;
}
//查找, 返回第一个值为x的节点存储位置
Node LocateNode(Node head, DataType x)
{
Node p;
if(head==NULL) return 0;
p=head->next;
while(p!=NULL)
{
if(p->info==x) return p;
p=p->next;
}
}
//定位p的前驱节点并删除p
Node DelNode(Node head, Node p)
{
Node temp, q=head;
if(head==NULL || head->next==NULL) return NULL;
if(q->next==p)
{
printf("该节点没有前驱节点\n");
}
while(q!=NULL)
{
if(q->next->next==p)
{
temp=q->next;
q->next=p;
return temp;
}
}
}
int main()
{
Node head, temp;
int n, t;
DataType x;
head=CreateNULLlink();
temp=head->next;
printf("请输入节点的数目: ");
scanf("%d", &n);
printf("\n请输入节点内容: ");
for(int i=0; i<n; i++)
{
scanf("%d", &x);
InsertLink(head, x);
}
// printf("%d", x);
// Printlink(head);
printf("\n头插法,请输入要插入的内容: ");
scanf("%d", &x);
InsertPre(head, x);
printf("\n插入后的链表:");
Printlink(head);
printf("\n请输入要删除内容的前驱: ");
scanf("%d", &x);
temp=LocateNode(head, x);
DelNode(head, temp);
printf("\n删除后的链表:");
Printlink(head);
return 0;
}
按照提示输入运行即可
运行结果如下