数据结构 创建单链表有关问题
数据结构 创建单链表问题
#include <stdlib.h>
#include <iostream.h>
#include <stdio.h>
#include <malloc.h>
#include <conio.h>
#define list_length 10
typedef struct LNode
{
int data ;
struct LNode *next ;
}LNode,*link_list;
void create_list(link_list &L,int n)
{
LNode *p_node;
int array[list_length];
L=(link_list)malloc(sizeof(LNode));
L->next = NULL ;
printf("input your data:");
for(int i=0 ; i<n ; i++)
{
scanf("%d",&array[i]);
}
for(int j=0 ; j<n ; ++j)
{
p_node=(link_list)malloc(sizeof(LNode));
p_node->data=array[i];
p_node->next=L->next;
L->next=p_node;
}
}
void main()
{
int length ;
link_list L ;
LNode *p_node;
printf("============================================\n");
printf("How many nodes do you want to create?\n");
scanf("%d",&length);
create_list(L,length);
p_node=L;
for(int i=0; i<length ; ++i)
{
p_node=p_node->next;
printf("%d' '",p_node->data);
}
printf("\n=============================================\n");
}
为什么结果是这样子的啊???
------解决方案--------------------
仅供参考
#include <stdlib.h>
#include <iostream.h>
#include <stdio.h>
#include <malloc.h>
#include <conio.h>
#define list_length 10
typedef struct LNode
{
int data ;
struct LNode *next ;
}LNode,*link_list;
void create_list(link_list &L,int n)
{
LNode *p_node;
int array[list_length];
L=(link_list)malloc(sizeof(LNode));
L->next = NULL ;
printf("input your data:");
for(int i=0 ; i<n ; i++)
{
scanf("%d",&array[i]);
}
for(int j=0 ; j<n ; ++j)
{
p_node=(link_list)malloc(sizeof(LNode));
p_node->data=array[i];
p_node->next=L->next;
L->next=p_node;
}
}
void main()
{
int length ;
link_list L ;
LNode *p_node;
printf("============================================\n");
printf("How many nodes do you want to create?\n");
scanf("%d",&length);
create_list(L,length);
p_node=L;
for(int i=0; i<length ; ++i)
{
p_node=p_node->next;
printf("%d' '",p_node->data);
}
printf("\n=============================================\n");
}
为什么结果是这样子的啊???
------解决方案--------------------
仅供参考
//假设带表头结点的单向链表头指针为head,试编写一个算法将值为5的结点插入到连接表的第k个结点前,删除第k个节点,并对该链表进行排序。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <time.h>
struct NODE {
int data;
struct NODE *next;
} H,*head,*p,*q,*s1,*s2,*s3,*s4,*s;
int i,j,k,n,t,m;
int main() {
srand(time(NULL));
//填写头节点数据
H.data=-1;
H.next=NULL;
head=&H;
//创建10个节点的单链表
p=head;
for (i=0;i<10;i++) {
q=(struct NODE *)malloc(sizeof(struct NODE));
if (NULL==q) return 1;
q->data=rand()%100;//填写0..99的随机值
q->next=NULL;
p->next=q;
p=q;
}
//输出整个单链表
s=head->next;
while (1) {
if (NULL==s) {
printf("\n");
break;
}
printf("%02d->",s->data);
s=s->next;
}
//将值为5的结点插入到单链表的第k个结点前
k=3;
n=0;
p=head;
while (1) {
if (NULL==p) {
break;
}
n++;
if (k==n) {
q=(struct NODE *)malloc(sizeof(struct NODE));
if (NULL==q) return 1;
q->data=5;
q->next=p->next;
p->next=q;
break;
}
p=p->next;
}
//输出整个单链表
s=head->next;
while (1) {
if (NULL==s) {
printf("\n");
break;
}
printf("%02d->",s->data);
s=s->next;
}
//删除第k个节点
k=5;
n=0;
p=head;
while (1) {