|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<stdlib.h>
#include<string.h>
#include <stdio.h>
#include <malloc.h>
struct Book
{
char a[20];
struct Book *next;
};
struct Book *initList(char *a)
{
struct Book *p=(struct Book *)malloc(sizeof(struct Book));
strcpy(p->a,a);
p->next = NULL;
return p;
}
void append(struct Book *head, char *a)
{
struct Book *p = head;
struct Book *pNew = (struct Book *)malloc(sizeof(struct Book));
while(p->next)
p = p->next; //这个是循环定位尾部。还有个是小甲鱼老师说的指针定位法。我想学习下这个指针法。
strcpy(pNew->a, a);
pNew->next = p->next;
p->next = pNew;
}
void printList(struct Book *head)
{
struct Book *p = head;
while(p)
{
printf("%s",p->a);
p = p->next;
}
}
int main(void)
{
struct Book *p = initList("ABC");
append(p,"DEF");
append(p,"GHI");
printList(p);
return 0 ;
}
- #include <stdio.h>
- #include<stdlib.h>
- #include<string.h>
- struct Book
- {
- char a[20];
- struct Book *next;
- };
- struct Book *initList(char *a)
- {
- struct Book *p=(struct Book *)malloc(sizeof(struct Book));
- strcpy(p->a,a);
- p->next = NULL;
- return p;
- }
- void append(struct Book *head, char *a)
- {
- struct Book *p = head;
- struct Book *pNew = (struct Book *)malloc(sizeof(struct Book));
- while(p->next) // <------------------------------------------------------重点,尾插法需要遍历
- p = p->next;
- strcpy(pNew->a, a);
- pNew->next = p->next;
- p->next = pNew;
- }
- void printList(struct Book *head)
- {
- struct Book *p = head;
- while(p)
- {
- printf("%s",p->a);
- p = p->next;
- }
- }
- int main(void)
- {
- struct Book *p = initList("ABC");
- append(p,"DEF");
- append(p,"GHI");
- printList(p);
- return 0 ;
- }
复制代码
|
-
-
|