本题要求实现不带有空头结点(dummy head node)的单链表操作集。
struct Node* findByIndex(struct Node *head, int index);
int insertByIndex(struct Node **phead, int index, int item);
int deleteByIndex(struct Node **phead, int index, int *pitem);
其中链表结构定义如下:
struct Node{
int data;
struct Node *next;
};
设链表结点从1
开始顺序编号,各函数阐述如下:struct Node* findByIndex(struct Node *head, int index)
查找序号为index
的结点,若找到则返回结点地址,否则返回NULL
int insertByIndex(struct Node **phead, int index, int item)
将元素item
插入到链表中且成为序号为index
的结点,若插入成功则返回1
,否则返回0
int deleteByIndex(struct Node **phead, int index, int *pitem)
将链表中序号为index
的结点删除并将其值放到pitem指向的变量中,若删除成功则返回1
,否则返回0
/* 测试程序仅为示例,实际的测试程序可能不同 */
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *next;
};
struct Node* initList() { return NULL; }
void printList(struct Node* head){
/* 细节省略 */
}
struct Node* createNode(int data){
struct Node *p;
p = (struct Node*)malloc(sizeof(struct Node));
if(!p) return NULL;
p->data = data;
p->next = NULL;
return p;
};
struct Node* findByIndex(struct Node *head, int index);
int insertByIndex(struct Node **phead, int index, int item);
int deleteByIndex(struct Node **phead, int index, int *pitem);
int main(){
struct Node *head;
head = initList();
int op, r, index, item;
struct Node *p;
scanf("%d", &op);
while(op){ //1:查找 2:插入 3:删除 其它:退出
switch(op){
case 1:
scanf("%d", &index);
p = findByIndex(head, index);
printf("%d\n", p ? p->data : 99999);
break;
case 2:
scanf("%d%d", &index, &item);
r = insertByIndex(&head, index, item);
printf("%d : ", r);
printList(head);
break;
case 3:
scanf("%d", &index);
item = 99999;
r = deleteByIndex(&head, index, &item);
printf("%d %d : ",r,item);
printList(head);
break;
default:
return 0;
}
scanf("%d", &op);
}
return 0;
}
/* 你的代码将被嵌在这里 */
2 1 10
2 1 20
2 2 30
2 4 5
2 6 6
1 2
1 5
3 1
3 2
0
结尾无空行
1 : 10,
1 : 20, 10,
1 : 20, 30, 10,
1 : 20, 30, 10, 5,
0 : 20, 30, 10, 5,
30
99999
1 20 : 30, 10, 5,
1 10 : 30, 5,
结尾无空行
?