读书人

一个关于循环的有关问题

发布时间: 2012-03-13 11:21:11 作者: rapoo

一个关于循环的问题~
node *create_list()
{
node *head, *p, *s;
int x;
char i = 0;
char cycle = 3;

head = (node *)malloc(sizeof(node));
p = head;

while(cycle--)
{
printf("input data: \n");
scanf("&c", &x);
if(x != 0)
{
s = (node *)malloc(sizeof(node));
s->data = x;
printf(" **********\n");
printf(" ** %d **\n", x);
printf(" **********\n");
p->pNext = s;
p = s;
i++;
}
}

head = head->pNext;

printf(" ##############################\n");
printf(" # The internal address is : \n");
printf(" # %d \n", head);
printf(" ##############################\n");

p->pNext = NULL;
printf("\n %d \n", head->data);
return head;
}

我的意图是:
创建一个链表,其中有3个节点,每次输入一个字符后把该字符存在一个节点中,然后再返回头节点的地址。

可是我一运行只是输入了一个字符之后就连续执行了下来,没办法输入第二三个节点的数据,这是怎么一回事啊?

[解决办法]
再给你一遍~
#include <stdio.h>
#include <stdlib.h>

struct node{
int data;
struct node * next;
};
typedef struct node* pNode;
typedef struct node Node;


void AddNode(pNode,int);
void PrintAll(pNode);
void AddNode2(pNode,int);
void DelNode(pNode,int);

int main()
{
int op;
int adddata;
int deldata;
Node head; //头节点
pNode phead=&head; //指向头节点的指针

head.data=0;
head.next=NULL;

scanf("%d",&op);
while(op)
{
switch(op)
{
case 1:
printf("Add Number:");
scanf("%d",&adddata);
AddNode(phead,adddata);
PrintAll(&head);
break;

case 2:
PrintAll(&head);
break;

case 3:
printf("Add Number:");
scanf("%d",&adddata);
AddNode2(phead,adddata);
break;

case 4:
printf("Del Number:");
scanf("%d",&deldata);
DelNode(phead,deldata);//PrintAll(&head);
break;

default:
printf("%s\n","????");
break;
}
scanf("%d",&op);
}

return 0;
}


void AddNode(pNode here,int want)
{
pNode temp;
temp=(pNode)malloc(sizeof(Node));
temp->data=want;
temp->next=NULL;
while(here->next)
here=here->next;
here->next=temp;
return;
}

void PrintAll(pNode here)
{
while(here)
{
printf("%d->",here->data);
here=here->next;
}
printf("\n");
return;
}

void AddNode2(pNode here,int want)
{
pNode temp;
temp=(pNode)malloc(sizeof(Node));
temp->data=want;
temp->next=here->next;
here->next=temp;
return;
}

void DelNode(pNode here,int want)
{
pNode temp=here;
pNode needdel;
while(temp && temp->next)
{
if(temp->next->data==want)
{
needdel=temp->next;


temp->next=temp->next->next;
free(needdel);
}
else
temp=temp->next;
}
return;
}

读书人网 >C语言

热点推荐