-->
当前位置:首页 > 题库 > 正文内容

程序填空题:Insert a node into a linked list

Luz4年前 (2021-05-10)题库855
The program below contains the **finding** and **inserting** operations of the Linked List **without** dummy head node.

The definition of the linked list is:
```
struct Node{
int data;
struct Node *next;
};
```
The nodes of linked list are numbered sequentially from `1`. (It means we count the nodes as `1,2,3,...` not `0,1,2,...`)

The functions are described as:

`struct Node* findByIndex(struct Node *head, int index)` ,search for the node whose index number is `index` and return its **address**. Return `NULL` if failed.

`int insertByIndex(struct Node **phead, int index, int item)` , insert a new node whose value is `item` and make its index number to be `index`. Return `1` if succeeded and `0` if failed.

e.g. for a linked list **head->12->34->56** ,

`findByIndex(head, 2)` will return the address of node `34`, and `insertByIndex(&head, 2, 78)` wil make the list become **head->12->78->34->56** .

Fill in the blanks to complete the function:

```c++
#include
#include
struct Node{
int data;
struct Node *next;
};
struct Node* initList(){ return NULL; }
void printList(struct Node* head){
/* details omitted */
}
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 i;
if(head==NULL || index < 1) return NULL;
for(i=1; @@[ head && inext,i++);
return @@[head](1);
}

int insertByIndex(struct Node **phead, int index, int item){
struct Node *tmp;
if(index < 1) return 0;
else if(index == 1){
tmp = createNode(item);
if(!tmp) return 0;
tmp->next = @@[ *phead ](1);
@@[ *phead ](1) = tmp;
}
else{
struct Node *p;
p = findByIndex(*phead, @@[ index-1 ](1) );
if(!p) return 0;
tmp = createNode(item);
if(!tmp) return 0;
tmp->next = @@[ p->next ](2);
p->next = tmp;
}
return 1;
}
```






答案:
第1空: head && i
第2空:head

第3空: *phead

第4空: *phead

第5空: index-1

第6空: p->next

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。