本帖最后由 364904690 于 2015-8-2 12:51 编辑
输出链表数据的print函数中,head指针已经移动到链表的末尾,为什么退出本次调用,下次再次调用print函数时,head指针仍然能从链表头节点开始输出。本人理解,在第二次调用前,首先要使head指针返回链表头结点。可是在这儿,没有再次赋值使head回到表头,但它确实是从表头开始输出的,想不明白!
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct node)
struct node //定义节点
{
char data;
struct node *next;
} *p, *q, *r,*t,*head;
struct node *creat() //创建4个链表节点并初始化
{
p=(struct node *)malloc(LEN); //开辟4个节点p,q,r,t
q=(struct node *)malloc(LEN);
r=(struct node *)malloc(LEN);
t=(struct node *)malloc(LEN);
p->data='A'; //初始化节点数据域
q->data='B';
r->data='C';
t->data='D';
p->next=q; //建立链接
q->next=r;
r->next=t;
t->next=NULL;
head=p;
return (head);
}
void print(struct node *head) //输出链表数据
{
do
{
printf("%c ",head->data);
head=head->next ; // 问题在这儿,问题在这儿
} while(head!=NULL);
printf("\n\n");
}
struct node * change(struct node *head) //更改节点顺序,将原来的A-B-C-D变为A-C-B-D
{
q->next=r->next;
p->next=r;
r->next=q;
return (head);
}
int main()
{
struct node *head;
head=creat();
print(head);
head=change(head);
print(head);
return 0;
}
|