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->next = NULL;
while(temp->next != NULL)
{
temp = temp->next;
}
printf("insert a num:");
scanf("%d",&lnew->num);
temp->next = lnew;
}
/*遍历链表,显示所有节点*/
void display(linklist &head)
{
linklist temp = head->next;
while(1)
{
printf("%d ",temp->num);
temp = temp->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<sum-1;i++)
{
temp1 = head->next;
while(temp1->next != NULL)
{
if(temp1->num > temp1->next->num)
{
temp2->num = temp1->num;
temp1->num = temp1->next->num;
temp1->next->num = temp2->num;
}
temp1 = temp1->next;
}
}
free(temp2);
}
int main()
{
int sum = 0;
//声明链表头结点
linklist head = (linklist)malloc(sizeof(lnode));
head->next = NULL;
char ac;
printf("continue(y?n)");
while(scanf("%c",&ac)&&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;
}