用C语言编程实现单向链表的基本操作: 1.插入元素2.删除元素 3.获取第 i 个结点的数据元素 4.判断元素是否存在 5.获取某个元素的下一个元素; NextElem ( L , cur _ e ,& next _ e );
时间: 2024-05-01 11:17:14 浏览: 73
1.插入元素
```
typedef struct Node {
int data;
struct Node *next;
} Node;
void insertNode(Node **head, int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Node *p = *head;
while (p->next != NULL) {
p = p->next;
}
p->next = newNode;
}
}
```
2.删除元素
```
void deleteNode(Node **head, int data) {
if (*head == NULL) {
return;
}
Node *p = *head;
if (p->data == data) {
*head = p->next;
free(p);
return;
}
while (p->next != NULL && p->next->data != data) {
p = p->next;
}
if (p->next != NULL) {
Node *q = p->next;
p->next = q->next;
free(q);
}
}
```
3.获取第 i 个结点的数据元素
```
int getData(Node *head, int i) {
if (head == NULL) {
return -1;
}
int cnt = 1;
Node *p = head;
while (p != NULL && cnt != i) {
p = p->next;
cnt++;
}
if (p == NULL) {
return -1;
} else {
return p->data;
}
}
```
4.判断元素是否存在
```
bool isExist(Node *head, int data) {
if (head == NULL) {
return false;
}
Node *p = head;
while (p != NULL) {
if (p->data == data) {
return true;
}
p = p->next;
}
return false;
}
```
5.获取某个元素的下一个元素; NextElem ( L , cur _ e )
```
int getNextElem(Node *head, int data) {
if (head == NULL) {
return -1;
}
Node *p = head;
while (p != NULL) {
if (p->data == data && p->next != NULL) {
return p->next->data;
}
p = p->next;
}
return -1;
}
```
阅读全文