单向链表与项目实战
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct sNode{
int data;
struct sNode *next;
};
struct sNode *CreateListFunc()
{
struct sNode *headNode=(struct sNode*)malloc(sizeof(struct sNode));
headNode->next=NULL;
return headNode;
}
struct sNode*CreateNodeFunc(int data)
{
struct sNode *newNode=(struct sNode*)malloc(sizeof(struct sNode));
newNode->data=data;
newNode->next=NULL;
return newNode;
}
void PrintListFunc(struct sNode *headNode)
{
struct sNode *pTemp=headNode->next;
while (pTemp)
{
printf("%d\t",pTemp->data);
pTemp=pTemp->next;
}
}
void InsertNodeHead(struct sNode *headNode,int data)
{
struct sNode *insertNode=CreateNodeFunc(data);
insertNode->next=headNode->next;
headNode->next=insertNode;
}
void DeleteNodeFunc(struct sNode *headNode,int posData)
{
struct sNode *posNode=headNode->next;
struct sNode *posNodeFront=headNode;
if(posNode==NULL)
printf("\n单链表为空\n\n");
else
{
while(posNode->data != posData)
{
posNodeFront=posNode;
posNode=posNodeFront->next;
if(posNode==NULL)
{
printf("\n无法找到指定位置.\n");
return;
}
}
posNodeFront->next=posNode->next;
free(posNode);
}
}
int main(int argc, char* argv[])
{
struct sNode *list=CreateListFunc();
printf("\n\n【单链表操作(插入/删除/输出)】\n");
PrintListFunc(list);
printf("初始化单链表操作:\n");
InsertNodeHead(list,55);
InsertNodeHead(list,77);
InsertNodeHead(list,44);
InsertNodeHead(list,22);
InsertNodeHead(list,99);
PrintListFunc(list);
printf("\n删除单链表中的结点操作:\n");
DeleteNodeFunc(list,22);
PrintListFunc(list);
printf("\n");
return 0;
}