本題要求實現鏈式表的操作集。
函式介面定義:
position find( list l, elementtype x );
list insert( list l, elementtype x, position p );
list delete( list l, position p );
其中list結構定義如下:
typedef struct lnode *ptrtolnode;
struct lnode ;
typedef ptrtolnode position;
typedef ptrtolnode list;
各個操作函式的定義為:
position find( list l, elementtype x ):返回線性表中首次出現x的位置。若找不到則返回error;
list insert( list l, elementtype x, position p ):將x插入在位置p指向的結點之前,返回鍊錶的表頭。如果引數p指向非法位置,則列印「wrong position for insertion」,返回error;
list delete( list l, position p ):將位置p的元素刪除並返回鍊錶的表頭。若引數p指向非法位置,則列印「wrong position for deletion」並返回error。
裁判測試程式樣例:
#include
#include
#define error null
typedef int elementtype;
typedef struct lnode *ptrtolnode;
struct lnode ;
typedef ptrtolnode position;
typedef ptrtolnode list;
position find( list l, elementtype x );
list insert( list l, elementtype x, position p );
list delete( list l, position p );
int main()
scanf("%d", &n);
while ( n-- )
}l = insert(l, x, null);
if ( l==error ) printf("wrong answer\n");
else
printf("%d is inserted as the last element.\n", x);
p = (position)malloc(sizeof(struct lnode));
tmp = insert(l, x, p);
if ( tmp!=error ) printf("wrong answer\n");
tmp = delete(l, p);
if ( tmp!=error ) printf("wrong answer\n");
for ( p=l; p; p = p->next ) printf("%d ", p->data);
return 0;/* 你的**將被嵌在這裡 */
輸入樣例:
612 2 4 87 10 2
42 12 87 5
輸出樣例:
2 is found and deleted.
12 is found and deleted.
87 is found and deleted.
finding error: 5 is not in.
5 is inserted as the last element.
wrong position for insertion
wrong position for deletion
10 4 2 5
position find
(list l, elementtype x)
return error;
}list insert
(list l, elementtype x, position p)
//情況2:如果正常插入中間部分
while
(l->next)
l=l->next;
}//情況3:如果p為null,即插入最後
if(p==
null
)//情況4:p指向非法位置
printf
("wrong position for insertion\n");
//觀察輸出樣例需要打換行符不然會影響整體格式
return error;
}list delete
(list l, position p)
if(l->next)prev=l->next;
while
(l->next)
//情況3:p是尾節點
if(prev==p&&prev->next==0)
prev=prev->next;
l=l->next;
}//情況4:非法情況
printf
("wrong position for deletion\n");
return error;
}
該題的**都是基本的單鏈表操作沒有難度,稍微有點繞的就是主函式的寫法和函式中的引數list l,需要觀察出該題函式insert採用的是頭插法:
基本上平時常用的是尾插法,這裡總結一下:
頭插法:
尾插法
除此之外進行鍊錶操作時需注意三段式:
插入時:在頭結點之前,在表中,在尾節點之後;
刪除時:刪除頭結點,刪除表中,刪除尾節點;
特殊情況特殊處理。
2020/3/10——by suki
6 5 鏈式表操作集 20分
函式介面定義 position find list l,elementtype x list insert list l,elementtype x,position p list delete list l,position p 其中list結構定義如下 typedef struct lnode ...
6 5 鏈式表操作集 20分
本題要求實現鏈式表的操作集。position find list l,elementtype x list insert list l,elementtype x,position p list delete list l,position p 其中list結構定義如下 typedef struct...
6 5 鏈式表操作集 20分
本題要求實現鏈式表的操作集。函式介面定義 position find list l,elementtype x list insert list l,elementtype x,position p list delete list l,position p 其中list結構定義如下 typedef...