cleey
望着那一丝海线,若隐若现。落日下的海霞,数不尽的美,看不完的醉
c链表
关于链表的学习,有指针等,实现了些小功能,学习用:
实现了链表的插入,删除,排序等功能;
贴出代码:


#include <stdio.h>
#include <stdlib.h>
/*声明一个结构体,包含以下几个内容,只是用到了num、next两个参数,待扩展*/
typedef struct node
{
int num;
char name[10];
struct node* next;
struct node* previous;
}lnode,*linklist;

/*新建一个节点*/
void insertnode(linklist head)
{
linklist temp = head;
linklist lnew = (linklist)malloc(sizeof(lnode));
lnew-&gt;next = NULL;
while(temp-&gt;next != NULL)
{
temp = temp-&gt;next;
}
printf("insert a num:");
scanf("%d",&amp;lnew-&gt;num);
temp-&gt;next = lnew;
}
/*遍历链表,显示所有节点*/
void display(linklist &amp;head)
{
linklist temp = head-&gt;next;
while(1)
{
printf("%d ",temp-&gt;num);
temp = temp-&gt;next;
if(temp==NULL)break;
}
}
/*对节点进行排序,升序*/
void lpsort(linklist head,int sum)
{
linklist temp1;
linklist temp2 = (linklist)malloc(sizeof(lnode));
int i=0,j=0;
/*冒泡排序*/
for(i=0;i&lt;sum-1;i++)
{
temp1 = head-&gt;next;
while(temp1-&gt;next != NULL)
{
if(temp1-&gt;num &gt; temp1-&gt;next-&gt;num)
{
temp2-&gt;num = temp1-&gt;num;
temp1-&gt;num = temp1-&gt;next-&gt;num;
temp1-&gt;next-&gt;num = temp2-&gt;num;
}
temp1 = temp1-&gt;next;
}
}
free(temp2);
}
int main()
{
int sum = 0;

//声明链表头结点
linklist head = (linklist)malloc(sizeof(lnode));
head-&gt;next = NULL;

char ac;
printf("continue(y?n)");
while(scanf("%c",&amp;ac)&amp;&amp;ac=='y')
{
insertnode(head);
getchar();
printf("continue(y?n)");
sum++;
}
printf("all:%d\n",sum);
display(head);


printf("\nafter sort\n");
lpsort(head,sum);
display(head);

free(head);// 释放内存
system("PAUSE");
return 0;
}

<< 上一篇 c语言库文件.h c指针 下一篇 >>
文章标签
随意 | Created At 2014 By William Clinton | 蜀ICP备14002619号-4 |