链表是一种物理存储结构上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。
单向链表(增、删、改、示)
#include <stdio.h>
#include <stdlib.h>
struct Node *CreateNewNode(struct Node *next);
void DisplyNode(struct Node *next);
void DeleteNode(struct Node *next);
struct Node *InserNode(struct Node *head,int NodeData);
struct Node
{
int data;
struct Node *Next;
};
int main(void)
{
int i = 0;
char c;
struct Node *head = NULL; //链表头指针
printf("Do you want to append a new node(Y/N)?");
scanf_s(" %c", &c);
while (c == 'Y' || c == 'y')
{
head = CreateNewNode(head);//向head为头指针的链表末尾添加节点
DisplyNode(head); //显示当前链表中的各节点的信息
printf("Do your want to append a new node(Y/N)");
scanf_s(" %c", &c);
i++;
}
printf("%d new nodes have been apended", i);
DeleteNode(head); //释放所有动态分配的内存
return 0;
}
/* 函数功能:新建一个节点并添加到链表末尾,返回添加节点后的链表的头指针 */
struct Node *CreateNewNode(struct Node *next)
{
struct Node *p=NULL,*pr = next;
int data;
p = (struct Node *)malloc(sizeof (struct Node));
if(p == NULL)
{
printf("No enough Mermeory\n");
exit(0);
}
if(next == NULL)
{
next = p;
}
else
{
while (pr->Next!=NULL)
{
pr = pr->Next;
}
pr->Next = p;
}
printf("Input node data\n");
scanf_s("%d",&data);
p->data = data;
p->Next = NULL;
return next;
}
void DisplyNode (struct Node *next)
{
struct Node *p =next;
int j =1;
while(p != NULL)
{
printf("%5d%10d\n",j,p->data);
p = p->Next;
j++;
}
}
void DeleteNode(struct Node *next)
{
struct Node *p =next,*pr = NULL;
while(p != NULL)
{
pr=p;
p = p->Next;
free(pr);
}
}
struct Node *InserNode(struct Node *head,int NodeData)
{
struct Node *p = NULL,*pr = head,*temp = NULL;
p = (struct Node *)malloc(sizeof (struct Node));
if(NULL == p)
{
printf("No enough memory!\n");
exit(0);
}
p->data = NodeData;
p->Next = NULL;
if(head == NULL) //如果原链表为空
{
head = p;
}
else //链表不为空,寻找插入节点
{
while(pr->data<NodeData&&pr->Next!=NULL)//遍历整个链表找到插入节点
{
temp = pr; //保存当前节点的指针
pr = pr->Next;
}
if(pr->data>= NodeData)
{
if(pr == head)//在链表头插入
{
p->Next = head; //头是新头节点的尾
head =p;
}
else
{
pr = temp; //指向当前节点的上一个节点
p->Next = pr->Next; //插入节指向下一节点
pr->Next = p; //指向插入节点
}
}
else
{
pr->Next = p;
}
}
return head;
}