#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct Node
{
int date;
struct Node * pNext;
}NODE, *PNODE;
PNODE create_list(void);
void traversal(PNODE);
bool is_empty(PNODE);
int len_list(PNODE);
void sort_list(PNODE);
bool insert_list(PNODE pHead,int pos, int val);
bool delete_list(PNODE pHead,int pos, int * val);
int main()
{
int val;
PNODE pHead;
pHead = create_list ();
traversal(pHead);
int len = len_list(pHead);
printf("链表的长度为%d\n",len);
delete_list (pHead, 2, &val);
//insert_list (pHead,3,100);
//sort_list(pHead);
traversal(pHead);
getchar();
getchar();
return 0;
}
PNODE create_list(void)
{
int len;
int val;
PNODE pHead = (PNODE)malloc(sizeof(NODE));
if(NULL == pHead)
{
printf("分配失败!");
exit(-1);
}
PNODE pTail = pHead;
pTail->pNext = NULL;
printf("请输入链表的元素个数:");
scanf("%d", &len);
for (int i=0; i<len; i++)
{
printf("请输入第%d个元素的值: ",i+1);
scanf("%d", &val);
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if(NULL == pNew)
{
printf("分配失败!");
exit(-1);
}
pNew->date = val;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}
void traversal(PNODE pHead)
{
PNODE p = pHead->pNext;
while (p != NULL)
{
printf("%d ",p->date);
p = p->pNext ;
}
printf("\n");
return;
}
bool is_empty(PNODE pHead)
{
if(NULL == pHead->pNext)
return true;
else
return false;
}
int len_list(PNODE pHead)
{
int len = 0;
PNODE p = pHead->pNext;
while(NULL != p)
{
++len;
p = p->pNext;
}
return len;
}
void sort_list(PNODE pHead)
{
int i,j;
PNODE p,q;
int t;
int len = len_list (pHead);
for(i=0,p=pHead->pNext; i<len-1; i++,p=p->pNext)
for(j=i+1,q=p->pNext; j<len; j++,q=q->pNext)
{
if(p->date > q->date )
{
t = p->date;
p->date = q->date ;
q->date = t;
}
}
}
bool insert_list(PNODE pHead,int pos, int val)
{
int i = 0;
PNODE p = pHead;
while(NULL != p && i<pos-1)
{
p = p->pNext;
++i;
}
if(NULL == p && i>pos-1)
return false;
PNODE pNew = (PNODE)malloc(sizeof(NODE));
pNew->date = val;
PNODE q = p->pNext;
p->pNext = pNew;
pNew->pNext = q;
return true;
}
bool delete_list(PNODE pHead,int pos, int * pval)
{
int i = 0;
PNODE p = pHead;
while(NULL != p->pNext && i<pos-1)
{
p = p->pNext;
++i;
}
if(NULL == p->pNext && i>pos-1)
return false;
*pval = p->pNext->date ;
PNODE q =p->pNext;
p->pNext = p->pNext->pNext;
free(q);
q = NULL;
return false;
}