#include
#include
#include
typedef struct Node
{
int data;//数据域
struct Node* pNext;//指针域
}Node,* pNode;
pNode create_list(void);
void traverse_list(pNode pHead);
int is_empty(pNode);
int length_list(pNode);
int insert_list(pNode, int, int);
int delete_list(pNode, int, int*);
void sort_list(pNode);
int main(void)
{
int len = 0;
int val;
pNode pHead = NULL;
pHead = create_list();//创建非循环单列
traverse_list(pHead);//遍历链表所有的值
if(is_empty(pHead))
{
printf("the list is empyt!\n");
}
len = length_list(pHead);
printf("the length of list is %d!\n",len);
sort_list(pHead);
traverse_list(pHead);
if(insert_list(pHead,2,99))
traverse_list(pHead);
else
printf("error!\n");
if(delete_list(pHead, 2, &val))
traverse_list(pHead);
else
printf("failed to delete!\n");
system("pause");
return 0;
}
pNode create_list(void)
{
int len;
int i;
int val;
pNode pTail;
pNode pNew;
pNode pHead;
pHead = (pNode)malloc(sizeof(Node));
if(NULL == pHead)
{
printf("分配失败,程序终止!");
exit(-1);
}
pTail = pHead;
pTail->pNext = NULL;//用pTail表示尾节点
printf("please input your num of nodes in the list:");
scanf("%d",&len);
for(i = 0; i < len; i++)
{
printf("please input the val of %dth node:",i+1);
scanf("%d",&val);
pNew = (pNode)malloc(sizeof(Node));
if(NULL == pHead)
{
printf("分配失败,程序终止!");
exit(-1);
}
pNew->data = val;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}
void traverse_list(pNode pHead)
{
pNode p = pHead->pNext;
while(NULL != p)
{
printf("%d ",p->data);
p = p->pNext;
}
printf("\n");
}
int is_empty(pNode pHead)
{
if(NULL != pHead->pNext)
return 0;
else
return 1;
}
int length_list(pNode pHead)
{
pNode p = pHead->pNext;
int len = 0;
while(NULL != p)
{
len++;
p = p->pNext;
}
return len;
}
void sort_list(pNode pHead)
{
int i, j, t;
pNode p,q;
int len = length_list(pHead);
for(i = 0, p = pHead->pNext;i < len-1;i++, p = p->pNext)//i,j是用来决定循环次数,在里面的排序方式没有影响
{
for(j = i+1,q = p->pNext; jpNext)
{
if(p->data > q->data)
{
t = p->data;
p->data = q->data;
q->data = t;
}
}
}
}
int insert_list(pNode pHead, int pos, int val)
{
int i = 0;
pNode pNew, q,p = pHead;
while(NULL != p && i < pos-1)
{
p = p->pNext;
i++;
}
if(i > pos-1||NULL == p)
return 0;
pNew = (pNode)malloc(sizeof(Node));
if(NULL == pNew)
{
printf("动态内存分配失败!\n");
exit(-1);
}
pNew->data = val;
q = p->pNext;
pNew->pNext = q;
return 1;
}
int delete_list(pNode pHead, int pos, int* pVal)
{
int i = 0;
pNode pNew, q,p;
p = pHead;
while(NULL != p && i < pos-1)
{
p = p->pNext;
i++;
}
if(i > pos-1||NULL == p)
return 0;
q = p->pNext;
*pVal = q->data;
//delete
p->pNext = p->pNext->pNext;
free(q);
q = NULL;
return 1;
}