本帖最后由 ing 于 2020-3-11 21:00 编辑
当我让2个指针(p 和 指针integrate)建立关系后,p指针删除元素,integrate也会减少
现在,删除一个元素,发现2个指针的内容都减少了
但是这里却不会,main 指针和 b1指针建立了关系
b1多次删去元素之后,发现只有会b1减少了元素
___________________________________________________
问题由此引起
p->next = p->next->next;
改成 p = p->next 就不会出现这种情况
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define KeyType int
#define Block 2
typedef struct link
{
KeyType data;
struct link *next;
}Link;
typedef struct
{
KeyType key;
int start;
}newIndex[Block];
void initLink(int array[], int start, int length, Link **p)
{
*p = (Link*)malloc(sizeof(Link));
Link *temp = *p;
//结束位置等于 总长度/分成的块数+起始位置
int e = length/Block + start;
for (size_t i = start; i < e; i++)
{
Link *a = (Link*)malloc(sizeof(Link));
a->data = array[i];
a->next = NULL;
temp->next = a;
temp = temp->next;
}
}
void merge(Link **main, Link *b1, Link *b2)
{
*main = b1;
while (b1->next)
{
b1 = b1->next;
}
while (b2)
{
b1->next = b2->next;
b1 = b1->next;
b2 = b2->next;
}
}
void swap(Link **integrate, int length)
{
Link *p = *integrate;
for (size_t i = 1; i < length; i++)
{
for (size_t j = 1; j < length; j++)
{
if (p->next->data > p->next->next->data)
{
Link *temp = p->next;
p->next->data = p->next->next->data;
p->next->next->data = temp->data;
}
p->next = p->next->next;
p->next->next = p->next->next->next;
if (!p->next->next) break;
}
}
}
void main()
{
int a[] = { 33, 42, 44, 38, 24, 48, 22, 12, 13,
8, 9, 20, 60, 58, 74, 49, 86, 53
};
Link *a1, *a2;
initLink(a, 0, 18, &a1);
initLink(a, 9, 18, &a2);
Link *integrate;
merge(&integrate,a1,a2);
swap(&integrate,18);
}
|