#include <stdio.h>
#include <stdlib.h>
typedef struct LinkedNode{
int score;
struct LinkedNode * next;
} LinkedNode_t, * LinkedNodeP_t;
LinkedNodeP_t insertNode(LinkedNodeP_t pHeader, int newScore) {
LinkedNodeP_t p1, p2;
p1 = pHeader;
p2 = pHeader;
if (p1 == NULL) {
p1 = (LinkedNodeP_t)malloc(sizeof(LinkedNode_t));
if (!p1) {
exit(-1);
}
p1->score = newScore;
p1->next = NULL;
return p1;
}
else if (p1->score >= newScore) {
p2 = (LinkedNodeP_t)malloc(sizeof(LinkedNode_t));
p2->score = newScore;
p2->next = p1;
return p2;
}
do {
p2 = p1->next;
if (p1->score < newScore && (!p2 || p2->score >= newScore)) {
LinkedNodeP_t p3 = malloc(sizeof(LinkedNode_t));
p3->score = newScore;
p3->next = p2;
p1->next = p3;
return pHeader;
}
else {
p1 = p2;
p2 = p2->next;
}
} while(1);
}
LinkedNodeP_t removeNode(LinkedNodeP_t pHeader, int scoreToRemove) {
LinkedNodeP_t p1, p2, p3;
p1 = pHeader;
p2 = NULL;
p3 = pHeader;
while(p1 && p1->score < scoreToRemove) {
p2 = p1;
p1 = p1->next;
}
while (p1 && p1->score == scoreToRemove) {
if (p2) {
p2->next = p1->next;
}
else {
p3 = p1->next;
}
LinkedNodeP_t p4 = p1;
p1 = p1->next;
free(p4);
}
return p3;
}
/**
?????????????????????С????
*/
LinkedNodeP_t revertList(LinkedNodeP_t pHeader) {
printf("not implemented yet\n");
return NULL;
}
/**
????????????????
*/
void freeList(LinkedNodeP_t pHeader) {
printf("not implemented yet\n");
return;
}
void outputList(LinkedNodeP_t pHeader) {
LinkedNodeP_t pLn = pHeader;
int count = 0;
printf("\n***************\noutput the linkedList\n");
while(pLn) {
count ++;
printf("%d\t", pLn->score);
pLn = pLn -> next;
}
printf("\n%d nodes totally\n**************\n\n\n", count);
}
int main( )
{
LinkedNodeP_t pSortedList = NULL;
printf("enter the scores to be inserted:\n");
do {
int temp;
scanf("%d", &temp);
if (temp <= 0) {
break;
}
pSortedList = insertNode(pSortedList, temp);
} while(1);
outputList(pSortedList);
printf("enter the one to be removed\n");
int temp2;
scanf("%d", &temp2);
pSortedList = removeNode(pSortedList, temp2);
outputList(pSortedList);
printf("now revert the list\n");
pSortedList = revertList(pSortedList);
outputList(pSortedList);
freeList(pSortedList);
return 0;
}
如何将一下代码实现链表反转和链表销毁
最新推荐文章于 2023-01-03 19:20:26 发布