坐火車時無聊,花了半小時的時間在練程式(用最單純的C Language),寫了一個List Data Structure.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node *NodePtr;
/* Define "Node" structure */
struct Node
{
int nNumber;
char sName[24];
NodePtr ptrNext;
};
typedef struct List *ListPtr;
/* Define "List" structure */
struct List
{
NodePtr ptrHead;
};
/* Function: void fnInsertToListHead(ListPtr ptrListL, NodePtr ptrTargetNode)
* Brief: Insert a node TargetNode into the front of ListL
* Input: ptrListL: pointer, points to the List L
ptrTargetNode: pointer, points to the wanna inserted node
* Output: The result of inserted list without return value.
*/
void fnInsertToListHead(ListPtr ptrListL, NodePtr ptrTargetNode)
{
NodePtr ptrCreateNode=(NodePtr) malloc(sizeof(Node));
ptrCreateNode->nNumber=ptrTargetNode->nNumber;
strcpy(ptrCreateNode->sName,ptrTargetNode->sName);
if(ptrListL->ptrHead == NULL)
{
ptrListL->ptrHead = ptrCreateNode;
ptrCreateNode->ptrNext=NULL;
}
else
{
NodePtr ptrTempNode = ptrListL->ptrHead;
ptrListL->ptrHead = ptrCreateNode;
ptrCreateNode->ptrNext = ptrTempNode;
}
}
/* Function: void fnScanList(ListPtr ptrL)
* Brief: Scan the List L, and show the elements of L.
* Input: ptrL: pointer to List L
* Output: None
*/
void fnScanList(ListPtr ptrL)
{
printf("Scan List:n");
NodePtr ptrN = ptrL->ptrHead;
while(ptrN != NULL)
{
printf("Number:%dt,Name:%sn",ptrN->nNumber,ptrN->sName);
ptrN=ptrN->ptrNext;
}
}
/* Function: void fnInitializeList(ListPtr ptrL)
* Brief: Initialize the List L
* Input: ptrL: pointer to List L
* Output: None.
*/
void fnInitializeList(ListPtr ptrL)
{
ptrL->ptrHead=NULL;
}
int main(int argc, char * argv[])
{
List myList;
/* Initialize myList */
fnInitializeList(&myList);
myList.ptrHead=NULL;
Node myNode1,myNode2;
/* Set myNode1 with (1,"Node1"), myNode2 with (2,"Node2") */
myNode1.nNumber=1;
myNode2.nNumber=2;
strcpy(myNode1.sName,"Node1");
strcpy(myNode2.sName,"Node2");
/* Insert myNode1 and myNode2 */
fnInsertToListHead(&myList, &myNode1);
fnInsertToListHead(&myList, &myNode2);
/* Scan myList */
fnScanList(&myList);
return 0;
}