#define MALLOC(dataType) malloc( sizeof(dataType) )
#define SCANF(pVal, val) scanf("%d", &val)
#define FREE(Point) free(Point)
typedef struct Node{
int data;
struct Node *pNext;
}NODE_T, *PNODE_T;
int scanfArray[8] = {2, 22, -13, -1, 54, 8, 118, 79};
void Create_List(PNODE_T pHead); // 创建链表
int Traverse_List(PNODE_T pHead); // 遍历链表
bool Is_Empty(PNODE_T pHead); // 判断链表是否为空
void Sort_List(PNODE_T pHead); // 排序链表
bool Insert_List(PNODE_T pHead, int pos, int val); // 插入链表一个元素
bool Delete_List(PNODE_T pHead, int pos, int *pVal); // 删除链表一个元素
int main(void)
{
int length, val;
PNODE_T pHead = (PNODE_T)MALLOC(NODE_T);
while(TRUE) {
Create_List(pHead);
Traverse_List(pHead);
//printf("List Length: %d\n",length);
Sort_List(pHead);
Traverse_List(pHead);
Insert_List(pHead, 4, 60);
Insert_List(pHead, 1, -16);
Traverse_List(pHead);
if(Delete_List(pHead, 1, &val)){
printf("delete success,val:%d\n", val);
}else{
printf("delete fail!\n");
}
Traverse_List(pHead);
Sort_List(pHead);
Traverse_List(pHead);
}
return 0;
}
void Create_List(PNODE_T pHead)
{
PNODE_T pTail = pHead;
if(NULL == pHead){
printf("Create List Fail!\n");
}else{
// printf("Create List Success!\n");
for(int i=0; i<8; i++)
{
PNODE_T pNew = (PNODE_T)MALLOC(NODE_T);
if(NULL == pNew){
printf("Allocation Fail!\n");
}else{
pTail->pNext = pNew;
pNew->data = scanfArray[i];
pTail = pNew;
}
}
pTail->pNext = NULL;
printf("Create Result: ");
}
}
int Traverse_List(PNODE_T pHead)
{
int length = 0;
PNODE_T p = pHead->pNext;
while(p != NULL){
printf(" %d",p->data);
p = p->pNext;
length++;
}
printf("\n");
return length;
}
bool Is_Empty(PNODE_T pHead)
{
if(NULL == pHead->pNext)
return true;
else
return false;
}
/* 排序该链表 */
void Sort_List(PNODE_T pHead)
{
if(Is_Empty(pHead)){
printf("List is emppty!");
}else{
int t, i, j;
PNODE_T p, q;
for(p=pHead->pNext,i=0; i<7; p=p->pNext,i++)
{
for(q=p->pNext,j=i+1; j<8; q=q->pNext,j++)
{
if(p->data > q->data){
t = p->data;
p->data = q->data;
q->data = t;
}
}
}
printf("Sort Result: ");
}
}
/* 在pos位置插入链表的一个元素,该元素的数据域的值存放在val中; pos大于0 */
bool Insert_List(PNODE_T pHead, int pos, int val)
{
int i = 0;
PNODE_T p = pHead;
while((NULL != p)&&(i < (pos-1))){
p = p->pNext;
i++;
}
if((NULL == p)||(i > (pos-1))) return false;
PNODE_T pNew = (PNODE_T)MALLOC(NODE_T);
if(NULL == pNew){
printf("Allocation Fail!\n");
}else{
pNew->data = val;
PNODE_T q = p->pNext;
p->pNext = pNew;
pNew->pNext = q;
return true;
}
}
/* 在pos位置删除链表的一个元素,并把节点的数据域的值存放到*pVal中; pos大于0 */
bool Delete_List(PNODE_T pHead, int pos, int *pVal)
{
int i = 0;
PNODE_T p = pHead;
while((NULL != p)&&(i < (pos-1))){
p = p->pNext;
i++;
}
if((NULL == p)||(i > (pos-1))) return false;
(*pVal) = p->pNext->data;
PNODE_T q = p->pNext;
p->pNext = p->pNext->pNext;
FREE(q);
return true;
}
链表程序.c
最新推荐文章于 2017-09-05 16:41:25 发布