#include<stdio.h>
#include<malloc.h>
#include<stdbool.h>
//定义链表
typedef struct ListNode{
int val;
struct ListNode* next;
}ListNode;
//链表初始化
ListNode* CreateList()
{
ListNode* Head=(ListNode*)malloc(sizeof(ListNode));
Head->next=NULL;
return Head;
}
//创建新结点
ListNode* CreateListNode()
{
ListNode* Node=(ListNode*)malloc(sizeof(ListNode));
printf("please input data:\n");
int data;
scanf("%d",&data);
Node->val=data;
Node->next=NULL;
return Node;
}
//头插法
void InsertNodeHead(ListNode* Head)
{
int i,n;
printf("InsertNodeHead:\n");
printf("please input size:\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
ListNode* newNode=CreateListNode();
newNode->next=Head->next;
Head->next=newNode;
}
}
//尾插法
void InsertNodeTail(ListNode* Head)
{
ListNode* Rear=(ListNode*)malloc(sizeof(ListNode));
Rear=Head;
int i,n;
printf("InsertNodeTail:\n");
printf("please input size\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
ListNode* newNode=CreateListNode();
newNode->next=Rear->next;
Rear->next=newNode;
Rear=newNode;
}
}
//打印输出链表
void PrintList(ListNode* Head)
{
ListNode* p=Head->next;
while(p)
{
printf("%d\t",p->val);
p=p->next;
}
printf("\n");
}
//指定位置删除
void DeleteNodeLocate(ListNode* Head)
{
int posData;
printf("please input posData:\n");
scanf("%d",&posData);
ListNode* p=Head;
ListNode* posNode=Head->next;
while(posNode->val!=posData)
{
p=p->next;
posNode=posNode->next;
if(posNode==NULL)
{
printf("fail to DeleteNodeLocate!\n");
return ;
}
}
p->next=posNode->next;
free(posNode);
}
//指定位置插入
void InsertNodeLocate(ListNode* Head)
{
int pos;
printf("please input pos:\n");
scanf("%d",&pos);
ListNode* p=Head;
ListNode* posNode=Head->next;
int i=0;
for(i;i<pos-1;i++)
{
p=p->next;
posNode=posNode->next;
}
ListNode* newNode=CreateListNode();
p->next=newNode;
newNode->next=posNode;
}
//判断是否为空
bool EmptyList(ListNode* Head)
{
if(Head->next)
{
printf("not Empty!\n");
return 0;
}
else
{
printf("Empty!\n");
return 1;
}
}
//清空链表
void ClearList(ListNode* Head)
{
ListNode *p,*q;
p=Head->next;
while(p )
{
q=p->next;
free(p);
p=q;
}
Head->next=NULL;
printf("Clear !\n");
}
//求链表长度
int Length(ListNode* Head)
{
ListNode* p=Head;
int count=0;
while(p->next!=NULL)
{
count++;
p=p->next;
}
printf("Length:%d\n",count);
return count;
}
int main(int argc, const char *argv[])
{
ListNode* Head=CreateList();
EmptyList(Head);
//InsertNodeTail(Head);
InsertNodeHead(Head);
PrintList(Head);
//ClearList(Head);
//EmptyList(Head);
//DeleteNodeLocate(Head);
//InsertNodeLocate(Head);
PrintList(Head);
Length(Head);
return 0;
}
链表代码(完整)
最新推荐文章于 2025-04-13 11:39:55 发布