链表的操作小结
#include <stdio.h>
#include "malloc.h"
typedef struct Node {
int data;
struct Node *pNext;
}*PNODE,NODE;
PNODE CreateList()
{
PNODE pHead = NULL;
PNODE pTail = NULL;
PNODE pNew = NULL;
int val, len;
if (pHead == NULL) {
pHead = (PNODE)malloc(sizeof(struct Node));
if (pHead == NULL) {
printf("create list failed.\n");
return NULL;
}
pTail = pHead;
pHead->pNext = NULL;
}
printf("Enter list len: ");
scanf("%d",&len);
while(len > 0) {
scanf("%d", &val);
pNew = (PNODE)malloc(sizeof(struct Node));
if (pNew == NULL) {
printf("create list failed under while\n");
free(pHead);
return NULL;
} else {
pNew->data = val;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
len--;
}
}
return pHead;
}
void TravelList(PNODE pHead)
{
PNODE tmpList = NULL;
if (pHead == NULL) {
return;
}
tmpList = pHead->pNext;
while (tmpList != NULL) {
printf("%d ",tmpList->data);
tmpList = tmpList->pNext;
}
printf("\n");
}
bool FreeAll(PNODE pHead)
{
PNODE tmpNode = NULL;
PNODE pList = pHead;
if (pHead == NULL) {
return false;
}
while(pList != NULL) {
tmpNode = pList->pNext;
free(pList);
pList = tmpNode;
}
return true;
}
bool InsertList(PNODE pHead, int pos, int val)
{
int i = 0;
PNODE pTmp = pHead;
PNODE q = NULL;
PNODE pNew = NULL;
while (pTmp != NULL && i < pos - 1) {
pTmp = pTmp->pNext;
i++;
}
if (i > pos - 1 || pTmp == NULL) {
return false;
}
pNew = (PNODE)malloc(sizeof(struct Node));
if (pNew == NULL) {
return false;
}
pNew->data = val;
q = pTmp->pNext;
pTmp->pNext = pNew;
pNew->pNext = q;
return true;
}
bool DeteleList(PNODE pHead, int pos, int *pVal)
{
int i = 0;
PNODE pTmp = pHead;
if (pHead == NULL || pVal == NULL) {
return false;
}
while (pTmp->pNext != NULL && i < pos - 1) {
pTmp = pTmp->pNext;
i++;
}
if (i > pos - 1 || pTmp->pNext == NULL) {
return false;
}
PNODE nextNode = pTmp->pNext;
*pVal = nextNode->data;
pTmp->pNext = nextNode->pNext;
free(nextNode);
nextNode = NULL;
}
int LengthList(PNODE pHead)
{
int len = 0;
PNODE p = pHead->pNext;
while (p != NULL) {
p = p->pNext;
len++;
}
return len;
}
bool SortList(PNODE pHead)
{
PNODE p = pHead->pNext;
PNODE q = NULL;
int i, j;
int len, tmp;
if (pHead == NULL) {
return false;
}
len = LengthList(pHead);
for (i = 0; i < len - 1; i++, p = p->pNext) {
for (j = 0, q = p->pNext; j < len - 1 - i; j++, q = q->pNext) {
if (p->data > q->data) {
tmp = p->data;
p->data = q->data;
q->data = tmp;
}
}
}
return true;
}
int main()
{
PNODE pHead = NULL;
int val = 0;
pHead = CreateList();
TravelList(pHead);
InsertList(pHead, 5, 99);
TravelList(pHead);
SortList(pHead);
TravelList(pHead);
FreeAll(pHead);
return 0;
}