线性表之单链表(下)
话不多说,只要写了几个线性表的操作,其中包括:表的反转,表的相邻节点间data的最大值,以及2个链表按照顺序大小合并
// 头文件:link_list.h
typedef int data_t;
typedef struct node{
data_t data;
struct node *next;
}listnode, *linklist;
// 倒置链表
int list_reverse(linklist H);
// 相邻节点之间的最大值
linklist list_adjmax(linklist H, data_t *value);
// 2个链表按照顺序大小合并
int list_merge(linklist H1, linklist H2);
// link_list.c
# include <stdio.h>
# include <stdlib.h>
# include "link_list.h"
// 链表倒置
int list_reverse(linklist H){
linklist p;
linklist q;
if (H == NULL){
printf("H is NULL\n");
return -1;
}
if (H->next == NULL || H->next->next == NULL){ // 只有一个节点
return 0;
}
p == H->next->next;
H->next->next == NULL;
while (p != NULL)
{
q = p;
p = p->next;
q->next = H->next; // 将第n个链表的尾部将第一个链表的头部相连
H->next = q; // 第n个链表的头和H相连
}
return 0;
}
// 链表相邻节点之间data的和取最大值
linklist list_adjmax(linklist H, data_t *value){
linklist p, q, r;
data_t sum;
if (H == NULL){
printf("H is NULL\n");
return NULL;
}
if (H->next == NULL || H->next->next == NULL || H->next->next->next == NULL){ // 只有2个链表情况
return H;
}
q = H->next;
p = H->next->next;
sum = q->data + p->data;
while (p->next != NULL)
{
p = p->next;
q = q->next;
if (sum < q->data + p->data){
sum = q->data + p->data;
r = q;
}
}
*value = sum; // *指针表示,指针的某个空间的值
return r;
}
int list_merge(linklist H1, linklist H2){
linklist p, q,r;
if (H1 == NULL || H2 == NULL){
printf("H1 || H2 is null\n");
return -1;
}
p = H1->next;
q = H2->next;
r = H1;
H1->next = NULL;
H2->next = NULL;
while (p && q)
{
if(p->data <= q->data){
r->next = p;
p = p->next;
r = r->next;
r->next = NULL;
}else{
r->next = q;
q = q->next;
r = r->next;
r->next = NULL;
}
}
if (p == NULL){
r->next = q;
}else{
r->next = p;
}
return 0;
}