码迷,mamicode.com
首页 > 编程语言 > 详细

链表操作C语言实现

时间:2015-09-29 22:06:40      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

#include<stdio.h>
#include<malloc.h>

typedef struct node {
int data;
struct node *next;
}node;
node *createlink()  //创建链表,从文件中读取数据
{
node *head =(node*)malloc(sizeof(node));
int t;
node *p;
node *q;
p=q=head;
FILE * r= fopen("demo.txt","r");
if(r==NULL)
{
printf("打开文件失败!");
return NULL;
}

while(fscanf(r,"%d",&t)!=EOF)
{
q= (node*)malloc(sizeof(node));
q->data=t;
p->next=q;
p=q;
}
p->next=NULL;
return head;
}
//输出链表到屏幕和文件output.txt
void outlink(node *head)
{
node *p=head->next;
FILE *w =fopen("output.txt","w");
if(w==NULL)
{
printf("打开文件失败!");
return;
}
while(p)
{
//输出链表节点数据到屏幕
printf("%d ",p->data);
//输出链表节点数据到文件output.txt
fprintf(w,"%d ",p->data);
p=p->next;
}
printf("\n");
fprintf(w,"\n");
fclose(w);
return;
}
node *BubbleSort(node* head)//冒泡排序
{
node *p = head->next;
node *pnext;
int temp;
while( p->next!= NULL) //把小元素都放到前面
{
pnext = p->next;
while(pnext->next != NULL)
{
if(p->data>pnext->data)
{
temp = pnext->data;
pnext->data = p->data;
p->data = temp;
}
pnext = pnext->next;
}
if(p->data>pnext->data)
{
temp = pnext->data;
pnext->data = p->data;
p->data = temp;
}
p = p->next;
}
return head;
}
void locate(node *head,int a)  查找元素位置
{
node *p = head->next;
while(p->data != a)
{
p = p->next;
}
printf("The position is %p",p);
}
void insert(node* head,int a)  //插入元素
{
node *p = (node *)malloc(sizeof(node));
p->next = head->next;
head->next = p;
p->data = a;
}
void Delete(node *head,int a) // 删除元素
{
node *p = head;
node *q = head->next;
while(q->data!=a)
{
p = p->next;
q = q->next;
}
p->next = q->next;
free(q);
}
/* 单链表反转/逆序 */
node *ListReverse(node* L)
{
node *current,*pnext,*prev;
if(L == NULL || L->next == NULL)
return L;
current = L->next; /* p1指向链表头节点的下一个节点 */
pnext = current->next;
current->next = NULL;
while(pnext)
{
prev = pnext->next;
pnext->next = current;
current = pnext;
pnext = prev;
}
//printf("current = %d,next = %d \n",current->data,current->next->data);
L->next = current; /* 将链表头节点指向p1 */
return L;
}

 

链表操作C语言实现

标签:

原文地址:http://www.cnblogs.com/Patrick-L/p/4847345.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!