#include
#include
typedef struct lnode
{
int data;
struct lnode *next;
}lnode,*linklist;
linklist creatheadinsert(linklist L,int a[],int n)
{
lnode *p,*r;
L->next=NULL;
r=L;
for(int i=0;i
{
p=(lnode *)malloc(sizeof(lnode));
p->data=a[i];
r->next=p;
r=p;
}
return L;
}
void deletelnode(linklist L,int x)
{
lnode *q=L->next,*pre=L,*p;
while(q!=NULL)
{
if(q->data==x)
{
p=q;
q=q->next;
pre->next=q;
free(p);
}
else
{
pre=q;
q=q->next;
}
}
}
int main()
{
linklist L=(lnode *)malloc(sizeof(lnode));
L->next=NULL;
int a[5]={1,2,2,3,5};
int n=5;
L=creatheadinsert(L,a,5);
deletelnode(L,2);
lnode *s=L->next;
while(s!=NULL)
{
printf("%d ",s->data);
s=s->next;
}
return 0;
}
linklist creatheadinsert(linklist L, int a[], int n)
{
lnode *p, *r;
L->next = NULL;
r = L;
for (int i = 0; i < n; i++)
{
p = (lnode *)malloc(sizeof(lnode));
p->data = a[i];
p->next=NULL;//+ 这一句要加上。
r->next = p;
r = p;
}
return L;
}
数据结构对单链表进行数据排序 http://bbs.csdn.net/topics/392201633
代码没什么问题,修改处见注释,供参考:
#include <stdio.h>
#include <stdlib.h>
typedef struct lnode
{
int data;
struct lnode* next;
}lnode, * linklist;
linklist creatheadinsert(linklist L, int a[], int n)
{
lnode* p, * r;
//L->next = NULL; 修改
r = L;
for (int i = 0; i < n; i++)
{
p = (lnode*)malloc(sizeof(lnode));
p->next = NULL; //修改
p->data = a[i];
r->next = p;
r = p;
}
return L;
}
void deletelnode(linklist L, int x)
{
lnode* q = L->next, * pre = L, * p;
while (q != NULL)
{
if (q->data == x)
{
p = q;
q = q->next;
pre->next = q;
free(p);
}
else
{
pre = q;
q = q->next;
}
}
}
int main()
{
linklist L = (lnode*)malloc(sizeof(lnode));
L->next = NULL;
int a[5] = { 1,2,2,3,5 };
int n = 5;
L = creatheadinsert(L, a, 5);
deletelnode(L, 2);
lnode* s = L->next;
while (s != NULL)
{
printf("%d ", s->data);
s = s->next;
}
return 0;
}