关闭

C语言单链表几个常用功能

93人阅读 评论(0) 收藏 举报
#include<stdio.h>
//创建结构体
struct list{
int a ;
struct list *next;
};


//创建链表
struct list * creatList(int nodeNumber){ //nodeNumber:初始链表中的节点数量(不包括头结点)
struct list *head;
struct list *node;
struct list *pointer;

int i;

head = (struct list*)malloc(sizeof(struct list));
head->a = -0x7FFFFFFF;
pointer = head;

for(i = 0 ; i < nodeNumber ; i++){
node = (struct list*)malloc(sizeof(struct list));
scanf("%d",&node->a);
node->next = NULL;
pointer->next = node;
pointer = node;
}
return head;
}


void printList(struct list *head){
struct list *pointer;
pointer = head->next;

while(pointer!= 0){
printf("%d,",pointer->a);
pointer = pointer->next;
}
printf("\n");
}


struct list * combineList(struct list * head1,struct list *head2){ //合并两个有序链表之后得到一个仍然有序的链表
struct list *p1;
struct list *p2;
struct list *q1;
struct list *q2;

q2 = head2->next;
p2 = q2->next;
p1 = head1;


while(q2 != NULL){

while(p1->next !=NULL){
if(q2->a >= p1->a && q2->a <= p1->next->a){
q2->next = p1->next;
p1->next = q2;

break;
}
p1 = p1->next;
}
if(p1->next == NULL){
p1->next = q2;
return head1;
}
q2 = p2;
if(q2 != NULL)
p2 = p2->next;
}
return head1;

}


struct list * swapNode(struct list *head,int x1,int x2){ //交换两个节点
struct list *p1;
struct list *p2;
struct list *s1;
struct list *s2;
struct list *pointer;


pointer = head;


while(pointer->next != NULL){
if(pointer->next->a == x1){
p1 = pointer;
s1 = pointer->next;
}
if(pointer->next->a == x2){
p2 = pointer;
s2 = pointer->next;
}
pointer = pointer->next;
}


p1->next = s1->next;
p2->next = s2->next;

s2->next = p1->next;
p1->next = s2;


s1->next = p2->next;
p2->next = s1;


return head;


}


struct list * delMinNode(struct list *head){ //删除最小节点


struct list *pointer;
struct list *minPriorAddress;

int min = head->next->a;

pointer = head;


while(pointer->next != NULL){
if(pointer->next->a <= min){
minPriorAddress = pointer;
}
pointer = pointer->next;
}


minPriorAddress->next = minPriorAddress->next->next;
return head;

}




struct list * reverseList(struct list *head){ //倒置链表
struct list *p;
struct list *w;
struct list *q;
struct list *pointer;
int i = 1;


q = head;
w = head->next;
p = head->next;


while(w!=NULL){
w = w->next;
p->next = q;

if(i == 1){
q->next = NULL;
i++;
}

q = p;
if(i == 2){
q->next = NULL;
i++;
}
p = w;
}
head->next = q;
return head;
}




struct list * insertNode(struct list *head,int x){ //在一个链表中插入值为X的节点
struct list * pointer;
struct list * creat;


creat = (struct list *)malloc(sizeof(struct list));


pointer = head;
creat->a = x;
creat->next = NULL;


while(pointer->next!=NULL){
if((creat->a >= pointer->a)&&(creat->a <= pointer->next->a)){
creat->next = pointer->next;
pointer->next = creat;
break;
}

pointer = pointer->next;
}
if(pointer->next == NULL){
pointer->next = creat;
}
return head;


}





0
0

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