链表简单操作
#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);
}
}