构造链表的一个注意事项

来源:互联网 发布:php socket 长连接 编辑:程序博客网 时间:2024/05/01 04:01

 看这个程序片断:

void push( st *head){
    st *p,*q;
     int i;
    q=head;
 
     while (scanf("%d",&i)){
     p=(st *)malloc(sizeof(st));

           p->data=i;
        p->next=head->next;
 //q->next=p;
 //q=p;
        head->next=p;
        printf("%d/n",(head->next->data));
     }
     while (getchar()!='/n')
           continue;
 //q->next=NULL;
    // return head;
     }

很简单,这个是构造一个链表,而这种构造方式其实是一种简单构造堆栈的方法。

若吧p=(st *)malloc(sizeof(st));这个语句放到while之外我们看看是什么东西?

void push( st *head){
    st *p,*q;
        int i;
    q=head;
    p=(st *)malloc(sizeof(st));
     while (scanf("%d",&i)){
  

           p->data=i;
        p->next=head->next;
 //q->next=p;
 //q=p;
        head->next=p;
        printf("%d/n",(head->next->data));
     }
     while (getchar()!='/n')
           continue;
 //q->next=NULL;
    // return head;
     }

两个程序看似差不多,但是后面的东西就有点郁闷了,它是一个在外面附带头节点的单节点循环链表,而不是单链表,它的节点一会因为输入值而变多,变化的只是本身的data值。

因为p在前面已经给分派好了,就是一个地址,以后的while中就是不停的在这个固定的地址上给data赋值而已。

所以想要让链表按照自己的想法变换就要没有加一个节点就要给p附一个地址。就是第一个程序片断那样。