关闭

c语言链表的创建、插入、删除、排序

262人阅读 评论(0) 收藏 举报
分类:
#include<stdio.h>
#include<malloc.h>


typedef struct Node
{
	int data;
	struct Node * pNext;
}NODE,*PNODE;

PNODE create_list(void);
void traverse_list(PNODE pHead);
bool is_empty(PNODE pHead);
int length_list(PNODE pHead);
void sort_list(PNODE pHead);
bool insert_list(PNODE pHead,int pos,int val);
bool delete_list(PNODE pHead,int pos,int * pVal);

PNODE create_list(void){
	int len;
	int val;
	int i;
	printf("请输入节点个数:");
	scanf("%d",&len);
	PNODE pHead = (PNODE)malloc(sizeof(NODE));
	pHead->pNext = NULL;
	PNODE pTail = pHead;
	if(NULL==pHead){
		printf("内存分配失败");
		exit(-1);
	}
	for(i = 0;i<len;i++){
		printf("请输入第%d个节点的值",i+1);	
		scanf("%d",&val);
		PNODE pNew = (PNODE)malloc(sizeof(NODE));
		if(NULL==pHead){
			printf("内存分配失败");
			exit(-1);
		}
		pNew->data=val;
		pTail->pNext=pNew;
		pNew->pNext = NULL;
		pTail = pNew;
	}
	return pHead;
}

void traverse_list(PNODE pHead){
	PNODE p = pHead->pNext;
	while(NULL!=p){
		printf("%d",p->data);
		p=p->pNext;
	}
	return;
}

bool is_empty(PNODE pHead){
	if(NULL == pHead->pNext){
		return true;
	}else{
		return false;
	}
}

int length_list(PNODE pHead){
	PNODE p = pHead->pNext;
	int cnt=0;
	while(NULL!=p){
		cnt = cnt+1;
		p=p->pNext;
	}
	return cnt;
}

void sort_list(PNODE pHead){
	int i,j,t;
	PNODE p,q;
	int len=length_list(pHead);
	for(i=0,p=pHead->pNext;i<len;i++,p=p->pNext){
		for(j=i+1,q=p->pNext;j<len;j++,q=q->pNext){
			t = p->data;
			p->data = q->data;
			q->data = t;
		}
	}
}

bool insert_list(PNODE pHead,int pos,int val){
	int i = 0;
	PNODE p = pHead;
	while(NULL != p && i<pos-1){
		p=p->pNext;
		i++;
	}
	if(i>pos-1 || NULL==p){
		return false;
	}
	PNODE pNew = (PNODE)malloc(sizeof(NODE));
	if(NULL==pNew){
		printf("分配内存失败");
		exit(-1);
	}
	pNew->data = val;
	pNew->pNext = p->pNext;
	p->pNext = pNew;
	
	return true;

}

bool delete_list(PNODE pHead,int pos,int * pVal){
	int i = 0;
	PNODE p = pHead;
	while(NULL != p->pNext && i<pos-1){
		p=p->pNext;
		i++;
	}
	if(i>pos-1 || NULL==p->pNext){
		return false;
	}
	PNODE pOld = p->pNext;
	*pVal = pOld->data;
	p->pNext = p->pNext->pNext;
	free(pOld);
	pOld = NULL;
	return true;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:14151次
    • 积分:296
    • 等级:
    • 排名:千里之外
    • 原创:14篇
    • 转载:10篇
    • 译文:0篇
    • 评论:6条
    文章分类
    最新评论