问题遇到的现象和发
麻烦帮看一下这里,为什么先用前插输入一个链表,然后用尾插再次输入链表的时候,不能把两次输入的链表连接在一起?
用代码块功能插入代码,请勿粘贴截图
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
typedef int Status;
typedef struct{
int x;
int y;
}ElemType;
typedef struct LNode{
int Length=0;
ElemType data;
struct LNode *next;
}LNode, *LinkList;
Status Init(LinkList &L)
{
L = new LNode;
if(!L) return ERROR;
L->next = NULL;
return OK;
}
Status Create_H(LinkList &L, int n)
{
LinkList p;
ElemType e;
for(int i = 0; i < n; i ++)
{
p = new LNode;
if(!p) return ERROR;
cin >> e.x >> e.y;
p->data = e;
p->next = L->next;
L->next = p;
}
return OK;
}
Status Create_T(LinkList &L, int n)
{
int Length;
LinkList r = L, p;
for(int i = Length; i < n+Length; i ++)
{
p = new LNode;
if(!p) return ERROR;
cin >> p->data.x >> p->data.y; //产生新节点
r->next = p;//尾结点连接新节点
r = p; //新节点变成尾结点
}
r->next = NULL;
return OK;
}
Status Trv(LinkList L)
{
LinkList p = L->next;
while(p)
{
cout << p->data.x << ' ' << p->data.y << endl;
p = p->next; //最后一个节点输出结束p变成NULL
}
return OK;
}
Status GetE(LinkList L, int w, ElemType &e)
{
LinkList p = L->next;
int j = 1;
while(p && j < w)
{
p = p->next;
j ++;
}
if(j > w || !p) return ERROR;//j > w代表w小 !p代表w大了
e = p->data;
return OK;
}
int cmp(ElemType a, ElemType b)
{
if(a.x == b.x && a.y == b.y) return 1;
else return 0;
}
LinkList Locate(LinkList L, ElemType e)
{
LinkList p = L->next;
while(p && !cmp(p->data, e))
{
p = p->next;
}
if(!p) return NULL;
return p;
}
Status Insert(LinkList &L, int w, ElemType e)
{
LinkList p = L;
int j = 0;
while(p && j < w - 1) //p代表前一个节点存在不存在
{
p = p->next;
j ++;
}
if(!p || j > w - 1) return ERROR; // !p代表w大了, j > w-1说明w小了
LinkList s = new LNode;
if(!s) return ERROR;
s->data = e; //先解决data,再解决线索
s->next = p->next;
p->next = s;
return OK;
}
Status Delete(LinkList &L, int w)
{
LinkList p = L;
int j = 0;
while(p->next && j < w - 1) //待删的节点存在,且前一个节点未找到
{
p = p->next;
j ++;
}
if(!(p->next) || j > w - 1) return ERROR;//第一个代表w大了, 第二个代表w小了
LinkList q = p->next;
p->next = q -> next;
delete q;
return OK;
}
int main()
{
LinkList L;
Init(L);
int n, w;
ElemType e;
cin >> n;
while(n --)
{
char op;
cin >> op;
switch(op)
{
case 'T':
int n;
cin >> n;
Create_T(L, n);
break;
case 'H':
cin >> n;
Create_H(L, n);
break;
case 'G':
int w;
cin >> w;
ElemType e;
GetE(L, w, e);
cout << e.x << ' ' << e.y << endl;
break;
case 'L':{
cin >> e.x >> e.y;
LinkList p = Locate(L, e);
cout << p->data.x << ' ' << p->data.y << endl;
break;}
case 'I': {
cin >> w;
cin >> e.x >> e.y;
Insert(L, w, e);
break;
}
case 'D':
cin >> w;
Delete(L, w);
break;
}
}
Trv(L);
return 0;
}