简单链表操作

链表简单操作

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>


//节点结构体
struct node{
	int data;  //数据域
	int key;   //索引域
	struct node*next; //下个节点
}

struct node *head = NULL; //定义初始化头节点
struct node *current = NULL; 

void printList(){
	struct node *ptr = head;
	printf("\n[ ");

	while(ptr != NULL){ //从头节点开始遍历,当节点不为空时遍历
		printf("(%d,%d) ",ptr->key,ptr->data); //打印节点索引以及数据
		ptr = ptr->next; //继续下一个节点
	}
	printf(" ]\n");
}

void insertFirst(int key,int data){
	struct node *link = (struct node*) malloc(sizeof(struct node)); //定义节点,为其开辟内存
	link->key = key; //节点key赋值
	link->data = data; //节点data赋值

	link->next=head; //节点下个节点指向头节点
	head = link; //节点赋值给头节点
	//至此代表一个单节点链表生成,下一个节点指向NULL
}

strcut node* deleteFirst(){
	struct node *tempLink = head;
	head = head->next;
	return tempLink;
}
bool isEmpty(){
	return head == NULL;
}

int length(){
	int length = 0;
	struct node *current;
	for(current = head;current!=NULL;current=current->next){
		length++;
	}
	return length;
}

struct node* find(int key){
	struct node* current = head;
	if(head == NULL){
		return NULL;
	}
	while(current->key!=key){
		if(current->next==NULL){
			return NULL;
		}else{
			current=current->next;
		}
	}
	return current;
}

struct node* delete(int key){
	struct node*current=head;//头节点开始
	struct node*previous=NULL;//临时节点
	if(head==NULL)
		return NULL;

	while(current->key!=key){//循环判断key值
		if(current->next==NULL){//没有下一个节点则退出
			return NULL
		}else{
			previous=current;//存储上一个节点
			current=current->next;//遍历下一个
		}
	}
	if(current==head){
		head=head->next;
	}else{//上一个节点的下一个直接指向当前节点的下一个
		previous->next=current->next;
	}
	return current;
}

void sort(){
	int i,j,k,tempKey,tempData;
	struct node *current;
	struct node *next;

	int size = length();
	k = size;

	for( i = 0; i < size - 1; i++, k--){
		current = head;
		next = head->next;
		for( j = 0; j < k; j++){
			if(current->data>next->data){
				tempData = current->data;
				current->data = next->data;
				next->data = tempData;

				tempKey = current->key;
				current->key = next->key;
				next->key=tempKey;
			}
			current = current->next;
			next = next->next;
		}
	}
}

void reverse(struct node** head_ref){
	struct node* prev = NULL;
	struct node* current = *head_ref;
	struct node* next;

	while(current != NULL){
		next = current->next;
		current->next = prev;
		prev = current;
		current = next;
	}
	*head_ref = prev;
}


void release(struct node** head){
	struct node*p;
	while(*head!=NULL){
		p=*head;
		*head=p->next;
		free(p);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值