C++链表,增删改查
//
// main.c
// homework_linkList
//
// Created by jiumiao on 15/7/23.
// Copyright (c) 2015年 jiumiao. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
typedef struct _NPC{
char name[20];
int attack;
int hp;
}NPC;
typedef struct _node{
NPC data;
struct _node *pNext;
}Node;
Node *head = NULL;//定义一个头节点
//加入节点
void addNode()
{
if (head == NULL) {
//head申请一个内存空间
head = malloc(sizeof(Node));
printf("请输入NPC的名字 攻击力 生命值:\n");
scanf("%s %d %d",head->data.name,&head->data.attack,&head->data.hp);
head->pNext=NULL;
} else {
Node *p = head;//指向头节点
while (p->pNext != NULL) {
p = p->pNext;
}
//申请内存空间
p->pNext = malloc(sizeof(Node));
p=p->pNext;
printf("请输入NPC的名字 攻击力 生命值:\n");
scanf("%s %d %d",p->data.name,&p->data.attack,&p->data.hp);
p->pNext = NULL;
}
printf("加入节点成功!\n");
}
//输出全部节点
void printAllNode()
{
Node *q = head;//指向头节点
while (q!=NULL) {
printf("名字为:%s,攻击力:%d。生命值:%d\n",q->data.name,q->data.attack,q->data.hp);
q=q->pNext;
}
printf("输出全部节点成功。\n");
}
//插入节点
void insertNode()
{
//创建一个新的节点
Node *newNode = malloc(sizeof(Node));
printf("请输入NPC的名字 攻击力 生命值:\n");
scanf("%s %d %d",newNode->data.name,&newNode->data.attack,&newNode->data.hp);
printf("请输入插入到第几个节点之后:\n");
int num;
scanf("%d",&num);
Node *p = head;//指向头节点
int count=0;//计数
while (p != NULL) {
count++;
if (count == num) {
break;
}
p=p->pNext;
}
Node *p2 = p->pNext;
p->pNext = newNode;
newNode->pNext = p2;
printf("插入节点成功。\n");
}
//改动节点
void modifyNode()
{
int num;
printf("请输入您要改动的节点:\n");
scanf("%d",&num);
Node *p = head;//指向头节点
int count = 0;//计数
while (p != NULL) {
count++;
if (count == num) {
break;
}
p=p->pNext;
}
printf("请输入NPC的名字 攻击力 生命值:\n");
scanf("%s %d %d",p->data.name,&p->data.attack,&p->data.hp);
printf("改动节点\n");
}
//删除节点
void deleteNode()
{
int num;
printf("请输入要删除第几个节点:\n");
scanf("%d",&num);
Node *p = head;//指向头节点
int count = 0;//统计节点数
while (p != NULL) {
count++;
p=p->pNext;
}
if (count == 1) {//删除头节点
p=head;
head = head->pNext;
free(p);//将原来的节点释放掉
}else if(count == num){//删除最后一个节点
Node *q = head;//指向头节点
while (q->pNext->pNext != NULL) {
q = q->pNext;
}
free(q->pNext->pNext);//释放节点
q->pNext = NULL;
}else{
Node *q1 = head;//指向头节点
int n=1;//统计节点数
while (q1 != NULL) {
n++;
if (n == num) {
break;
}
q1 = q1->pNext;
}
Node * p2 = q1->pNext;
q1->pNext = p2->pNext;//q1->pNext->pNext
free(p2);
}
printf("删除节点成功!\n");
}
int main(int argc, const char * argv[]) {
// 怎样实现一个链表。当用户希望加入NPC的时候,能够在链表上添加一个NPC变量的节点,输出全部的节点。插入,改动。删除,退出系统
printf("NPC管理系统!
\n");
int num;
while (1) {
printf("\n1.加入NPC节点\n");
printf("2.输出全部NPC的节点\n");
printf("3.插入NPC的节点\n");
printf("4.改动NPC的节点\n");
printf("5.删除NPC的节点\n");
printf("6.退出系统\n");
printf("请选择所需操作:\n");
scanf("%d",&num);
switch (num) {
case 1:
addNode();//加入节点
break;
case 2:
printAllNode();//输出全部节点
break;
case 3:
insertNode();//插入节点
break;
case 4:
modifyNode();//改动节点
break;
case 5:
deleteNode();//删除节点
break;
case 6:
return 0;
break;
default:
break;
}
}
return 0;
}