0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## 单向链表标准写法（C格式）

whonee 2012-11-12 09:33:00 浏览1248

```/************************************
*
*			Include File
*
*************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/************************************
*
*			Data Definitions
*
*************************************/

struct Node
{
char* City;
int 	Temp;
struct Node* Next;
};

typedef struct Node* Link;

int NodeCount = 0;

/************************************
*
*			Functions Declarations
*
*************************************/

/** Initialize List **/
void CreateList(void);

/** Add Node **/

/**Delete Node **/

/** Free Node **/

/** Handle Duplication Node **/

/** Show List Of Nodes **/
void ShowNode(void);

/** Compare Two Node**/

/************************************
*
*			Functions Definitions
*
*************************************/

int
{
Link pn, 		/* local copy of node to be add */
prev,	/* points to previous node */
curr;	/* points to node being examined */

struct Node dummy;
int 	i ;

pn = (Link)malloc(sizeof(struct Node));
if(pn == NULL)
return 0;

prev= &dummy;

for(;;prev = curr,curr= curr->Next)
{
if(curr = NULL) break;
i = NodeCmp(pn, curr);
if(i <= 0) break;
}

if(curr && i == 0)
if(DuplicationNode(curr, pn))
return(1);

prev->Next = pn;

pn->Next = curr;

NodeCount += 1;
return(1);
}

int
DuplicationNode(
{
FreeNode(duplication);

return (0);
}

int
DeleteNode(
{
prev;

int   i ;

return(0);

for( prev = NULL,curr = Head;
curr != NULL &&(i = NodeCmp(to_delete, curr))>0;
prev = curr,curr = curr->Next);

if(curr !=NULL && i==0)
{
if(prev)
prev->Next = curr->Next;
else

FreeNode(curr);

NodeCount -= 1;

return(1);
}
return(0);

}

int
NodeCmp(
{

if(a->Temp != b->Temp)
return (a->Temp - b->Temp);

return strcmp(a->City,b->City);
}

void
CreateList(
void)
{
NodeCount = 0;
}

void
FreeNode(
{
free(n->City);
free(n);
}

void
ShowNode(
void)
{

int count,median;

for(count = 0,pn = Head;pn;pn = pn->Next)
count += 1;

median = count /2 + 1;

if(count)
{
count = 0;

for(pn = Head ;pn;pn = pn->Next)
{
printf("%-20s : %3d " ,pn->City,pn->Temp);
count += 1;
if(count == median)
printf(" -----Midian ------");

printf("\n");
}
}
else
printf("Empty List !\n");

}

int
main(
int argc,
char* argv[])
{
FILE* fin;
char buffer[128];

struct Node n;

if(argc != 2)
{
fprintf(stderr ,"Usage : citytemp filename .ext \n ");

exit(EXIT_FAILURE);
}

fin = fopen(argv[1],"rt");
if(fin == NULL)
{
fprintf(stderr ,"Cann't open file %s\n  ",argv[2]);

exit(EXIT_FAILURE);
}

CreateList();

while(!feof(fin))
{
if(fgets(buffer,127,fin) == NULL) break;

buffer[strlen(buffer) -1] = '\0';

n.City = strdup(buffer + 3);

buffer[3] = '\0';

n.Temp = atoi(buffer);

{
fprintf(stderr ," Error adding node . Aborting !\n");

exit(EXIT_FAILURE);
}
}

ShowNode();

printf("\n");

ShowNode();

{
printf("\n");
ShowNode();
}

printf("\n");

ShowNode();

fclose(fin);

return (EXIT_SUCCESS);

}```

whonee
+ 关注