6-5-链式表操作集-函数题

6-5-链式表操作集-函数题

  • 解题代码
  • 测试结果
  • 问题整理

解题代码

Position Find(List L, ElementType X) {
     
	Position loc = ERROR;
	if (L) {
     
		List t = L;
		while (t) {
     
			if (t->Data == X) {
     
				loc = t;
				break;
			}
			else {
     
				t = t->Next;
			}
		}
	}
	return loc;
}
ElementType Legal(List L, List P) {
     
	ElementType ret = 0;
	if (!L) {
     
		if (!P) ret = 1;
	}
	else {
     
		if (!P) ret = 1;
		else {
     
			List t = L;
			while (t) {
     
				if (t == P) {
     
					ret = 1;
					break;
				}
				else {
     
					t = t->Next;
				}
			}
		}
	}
	return ret;
}
List Insert(List L, ElementType X, Position P) {
     
	List new = ERROR;
	ElementType flag=Legal(L, P);
	if (flag) {
     
		List add = (List)malloc(sizeof(struct LNode));
		add->Data = X;
		add->Next = P;
		List t = L;
		if (!t)	new = add;
		else {
     
			if (t == P) new = add;
			else {
     
				while (t) {
     
					if (t->Next == P) {
     
						t->Next = add;
						new = L;
                        break;
					}else{
     
                        t=t->Next;
                    }
                   
				}
			}
		}
	}
	else {
     
		printf("Wrong Position for Insertion\n");
	}
	return new;
}
List Delete(List L, Position P) {
     
	List new = ERROR;
	ElementType flag = Legal(L, P);
	if (flag) {
     
		if (L) {
     
			if (!P) new = L;
			else {
     
				List p = L, t = p->Next;
				if (P == p) {
     
					free(P); 
					new = t;
				}
				else {
     
					while (p) {
     
						if (t == P) {
     
							t = t->Next;
							p->Next = t;
							free(P);
							new = L;
                            break;
						}
						else {
     
							p = t;
							t = t->Next;
						}
					}
				}
			}
		}
	}
	else {
     
		printf("Wrong Position for Deletion\n");
	}
	return new;
}

测试结果

6-5-链式表操作集-函数题_第1张图片

问题整理

1.小心忘记break导致的段错误。
2.小心循环体内循环判断条件出错导致的运行超时。

你可能感兴趣的:(6-5-链式表操作集-函数题)