练习一:
实现:将元素e构造成结点,插入链表并使之成为链表的第i个结点。(i从1开始)
要求:
- 链表不带头结点的链表(即链表中的第一个节点就为有数据有效节点,当链表为空链表时,list为NULL)。
- 如果位置i不合理,则使之成为第一个结点。
- 函数返回值为链表的首节点的地址。
typedef struct node { int data; struct node * next; } Node; Node * insert(Node * list, int i, int e) { // TODO: //在这里面插入所写的代码 }
答案(不止一种,这里只是示例):
#include<stdio.h> typedef struct node { int data; struct node* next; } Node; Node* insert(Node* list, int i, int e) { // TODO: int m = 0; Node* a = NULL, * p = list; Node* b = (Node*)malloc(sizeof(Node)); b->data = e; b->next = NULL; while (p && m < (m - 1)) { m++; a = p; p = p->next; } if (m > 1 || p) { b->next = a->next; a->next = b; } else { b->next = list; list = b; } return list; }
练习二:
实现:将元素e构造成结点,插入第一个值为x的链表结点之前。
要求:
- 链表不带头结点(同练习一)。
- 如果没有x,则使之成为第一个结点。
- 函数返回值为链表的首节点的地址。
typedef struct Node { int data; struct Node * next; } Node; Node * insert(Node * list, int x, int e) { // TODO: //在这里面完善代码 }
答案(不止一种,这里只是示例):
#include<stdio.h> #include<stdlib.h> typedef struct Node { int data; struct Node* next; } Node; Node* insert(Node* list, int x, int e) { // TODO: Node* a = NULL, * p = list; Node* b = (Node*)malloc(sizeof(Node)); b->data = e; b->next = NULL; while (p && p->data != x) { a = p; p = p->next; } if (p || p != list) { b->next = a->next; a->next = b; } else { b->next = list; list = b; } return list; }