链表基础操作及其逆置

纠结了很久的一道链表题。果然我数据结构学得好渣。纠结了大约两个星期。最后提交作业的时间都截止了,还没交,再交的时候过期了,交不了了。只好跟老师说声,然后她又改了时间。

最后总结出了是我的指针和结构体学得不好额。哎,谁让学校只教了我们半本C语言。。。还得靠自学。

其实就算是教了前半本C,我当时学得也是渣的可以。那半本还不都是后来假期每天敲代码的时候掌握的。。

#include <stdio.h>
#include <malloc.h>

typedef int ElemType;  

typedef struct LNode    /*定义结点结构体类型*/
{ 	
	ElemType data;		/*数据域*/
	struct LNode *next; 	/*指针域*/
} LNode;

LNode *creatlist(int n)     	/*创建一个含 n 个结点的链表*/
{
   LNode *head=NULL, *p;
   int i;
   for(i=0;i<n;i++)      		/*创建有n个结点的链式基本线性表*/
   {
        p=(LNode *)malloc(sizeof(LNode)); 	/*生成新结点*/
        printf("record %d\n",i+1);
        printf("input data:");
        scanf("%d",&p->data);  	/*对新结点的数据域赋值*/
        if(i==0)         		/*创建链式基本线性表的头结点*/
        {
            head=p;  
            head->next=NULL;
        }
        else           			/*创建链式基本线性表中的其他结点*/
        {
           p->next=head;
           head=p;
        }
        }
    return(head);
}

void DispList(LNode *head)	/*输出单链表*/
{
    LNode *p;
	p=head;
    while (p!=NULL) 
	{
		printf("%4d ",p->data);
		p=p->next;
    }
    printf("\n");
}

LNode *reverlist(LNode *head) 	/*逆置链式基本线性表*/
{
    	
    	LNode *p,*q,*r;
		p=head;
		q=p->next;
		while(q!=NULL)
		{
			r=q->next;
			q->next=p;
			p=q;
			q=r;
		}
		head->next=NULL;
		head=p;
	
    return(head);
}
void main()
{
    LNode *head=NULL,*p;
    int n;
    printf("input number of node:"); 	/*输入链式基本线性表的结点数*/
    scanf("%d",&n);

    head=creatlist(n);       			/*创建链式基本线性表*/
    printf("\n\n逆置前");
    DispList(head);         			/*输出创建成功的链式基本线性表*/
    printf("\n");

    p=reverlist(head);        		/*将链式基本线性表逆置*/

    printf("\n\n逆置后");
    DispList(p);     				/*输出逆置后的线性表*/
}



posted on 2013-04-10 23:02  果冻虾仁  阅读(143)  评论(0编辑  收藏  举报

导航