|
发表于 2015-8-3 08:31:04
|
显示全部楼层
#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");
}
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;
}
按照红色的部分的 能达到楼主的效果 不过代码运行会出错 因为第一次的print已经到表尾
任何变量(包括指针)作为参数在函数之间传递时, 编译器都会默认创建一个临时变量
你在函数内部修改的仅仅是这个临时变量 楼主对这个临时变量的位置进行了修改 但是函数体结束时
这个临时变量就会消失 而外部的变量 并没有得到实质的变化
函数体内想要对外部的指针变量进行实际操作, 要么传指针的引用 要么传递二级指针
建议楼主看看经典的swap函数 进行下深刻的理解传值和传址的区别 |
|