C语言链表的问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C语言链表的问题相关的知识,希望对你有一定的参考价值。
建立一个含有5个结点的单链表,每个结点的数据域由键盘输入,然后将链表接点的值反向输出?这里的反向输出怎么实现啊?求源代码,高人解决!!
链表不用逆置,也不用数组,只要在创建的时候采用头插法,就可以实现链表的反向输出!#include <stdlib.h>
#include <stdio.h>
typedef struct LNode
int data;
struct LNode*next;
Link,*List;
void ListInit(List *L)
/* 产生头结点,并使L指向此头结点 */
*L = (List)malloc(sizeof(struct LNode));
if( !*L ) /* 存储分配失败 */
exit(-1);
(*L)->next = NULL; /* 指针域为空 */
//创建链表,采用头插法,输出的时候就是逆向的
void ListCreate(List L)
int data;
List s, p;
p = L;
while (1)
printf("input data(0 to exit):");
scanf("%d", &data);
if(data == 0) break;
s = (List)malloc(sizeof(LNode));
s->data = data;
s->next = L->next;
L->next = s;
//链表打印
void ListPrint(List L)
List p = L->next;
while (p)
printf("%d ", p->data);
p = p->next;
printf("\n");
int main(void)
List L;
//链表初始化
ListInit(&L);
//链表创建
ListCreate(L);
//打印链表
ListPrint(L);
system("Pause");
return 0;
参考技术A 从头到尾的数据用数组存起来啊,然后把数组从尾到头输出就可以了,没说不让用数组吧。另一个方法是迭代输出,也可以的,如下:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct link
int num;
struct link *next;
;
void print(struct link *h)
if(h->next!=NULL)
print(h->next);
printf(" %d ",h->num);
struct link* creat()
struct link *h1,*p1,*p2;
int i;
h1=(struct link*)malloc(sizeof(struct link));
scanf("%d",&h1->num);
p2=h1;
for(i=0;i<4;i++)
p1=(struct link*)malloc(sizeof(struct link));
p1->next=NULL;
p2->next=p1;
p2=p1;
scanf("%d",&p1->num);
return h1;
int main()
struct link * head;
head=creat();
print(head);
system("pause");
return 0;
参考技术B #include<stdio.h>
#include<stdlib.h>
typedef struct NODE
int num;
struct NODE *next;
node;
void print(node *head)
if(head->next) print(head->next);
printf("%d\t",head->num);
int main()
node a[5];
for(int i = 0; i < 5; i++)
scanf("%d",&a[i].num);
a[i].next = a + a[i].num;
a[4].next = NULL;
for(node *head = a; head; printf("%d\t",head->num),head = head->next);
putchar(10);
print(a);
putchar(10);
return 0;
参考技术C #include <stdio.h>
#include <stdlib.h>
typedef struct node
int data;
struct node *next;
Node;
//创建链表
Node *fun1(void)
int i;
Node *head, *p, *q;
head = NULL;
scanf("%d", &i);
while(i != 0)
p = (Node *)malloc(sizeof(Node));
p->data = i;
if(head == NULL)
q = head = p;
else
q->next = p;
q = p;
scanf("%d", &i);
p->next = NULL;
return head;
//链表的逆置
Node *fun2(Node *head)
Node *p, *q, *r;
p = head;
q=r=NULL;
while(p)
q = p->next;
p->next = r;
r = p;
p = q;
return r;
//输出链表
void fun3(Node *head)
Node *p;
p = head;
while(p)
printf("%d\t", p->data);
p = p->next;
int main(void)
Node *head;
head = fun1();
fun3(head);
head = fun2(head);
fun3(head);
return 0;
参考技术D #include <stdio.h>;
#include <stdlib.h>;
#define NUM 5
struct t
int data;
struct t* next;
*h;
main()
int i,j;
struct t *p,*q;
h=(struct t*)malloc(sizeof(struct t));
q=h;
for(i=0;i<NUM;i++)
p=(struct t*)malloc(sizeof(struct t));
scanf("%d",&p->data);
p->next=NULL;
q->next=p;
q=p;
for(j=i;j>0;j--)
i=j;
p=h;
while(i>0)
p=p->next;
i--;
printf("%d\n",p->data);
以上是关于C语言链表的问题的主要内容,如果未能解决你的问题,请参考以下文章