单向链表(C语言)

定义数据

#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0

typedef int Status;
typedef int ElemType;
/* 定义节点 */
typedef struct Node {
	ElemType val;
	struct Node *next;
} Node, *PNode;
/* 定义链表 */ 
typedef struct LinkList {
	PNode head;
	int length;
} LinkList, *PLinkList;

创建链表

/* 将数组转为链表 */
LinkList transfor(ElemType *array, int size) {
	PLinkList plist = (PLinkList) malloc(sizeof(LinkList));
	plist->head = (PNode) malloc(sizeof(Node));
	plist->length = 0;
	PNode p = plist->head;
	PNode q = NULL;
	int i;
	for(i = 0; i < size; i++) {
		q = (PNode) malloc(sizeof(Node));
		q->val = array[i];
		p->next = q;
		p = q;
		plist->length++;
	}
	p->next = NULL;
	return *plist;
}

打印链表

void printAll(LinkList list) {
	PNode p = list.head;
	int i;
	printf("{");
	for(i = 0; i < list.length; i++) {
		p = p->next;
		printf(" %d", p->val);
	}
	printf(" }\n");
} 

头插法添加节点

/* 在头部添加节点 */
void addHead(PLinkList plist, ElemType e) {
	PNode head = plist->head;
	PNode p = (PNode) malloc(sizeof(Node));
	p->val = e;
	p->next = head->next;
	head->next = p;
	plist->length++;
}

尾插法添加节点

/* 在尾部添加节点 */
void addTail(PLinkList plist, ElemType e) {
	PNode p = plist->head;
	PNode q = (PNode) malloc(sizeof(Node));
	q->val = e;
	while(p->next) {
		p = p->next;
	}
	p->next = q;
	q->next = NULL;
	plist->length++;
}

在指定位置插入节点

Status insert(PLinkList plist, int i, ElemType e) {
	if(i < 1 || i > plist->length + 1) {
		printf("插入位置越界\n");
		return ERROR;
	}
	PNode p = plist->head;
	int j = 1;
	while(j < i) {
		p = p->next;
		j++;
	}
	PNode q = (PNode) malloc(sizeof(Node));
	q->val = e;
	q->next = p->next;
	p->next = q;
	plist->length++; 
	return OK;
}

删除节点

Status del(PLinkList plist, int i, ElemType *e) {
	if(i < 1 || i > plist->length) {
		printf("删除位置越界\n");
		return ERROR;
	}
	PNode p = plist->head;
	int j = 1;
	while(j < i) {
		p = p->next;
		j++;
	} 
	PNode q = p->next;
	*e = q->val;
	p->next = q->next;
	free(q);
	plist->length--;
	return OK;
}

定位元素位置

/* 定位元素在表中的位置 */
int locateElem(LinkList list, ElemType e) {
	PNode p = list.head->next;
	int i = 1;
	while(p) {
		if(p->val == e) {
			return i;
		}
		p = p->next;
		i++;
	} 
	return -1;
}

判断元素是否在表中

Status inList(LinkList list, ElemType e) {
	return locateElem(list, e) != -1 ? TRUE : FALSE;
}

清空链表

void clearList(PLinkList plist) {
	if(!plist) {
		return;
	}
	PNode p = plist->head->next;
	PNode q = NULL;
	if(p) {
		q = p->next;
		free(p);
		p = q; 
	}
	plist->length = 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值