单链表的插入和删除代码主程序
时间: 2023-11-06 20:04:39 浏览: 36
很高兴回答你的问题!以下是单链表插入和删除的基本代码框架,你可以根据具体的需求进行修改和完善。
单链表插入:
```
/* 定义链表结构体和节点结构体 */
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
/* 在链表头部插入节点 */
ListNode *insert(ListNode *head, int val) {
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->val = val;
node->next = head;
return node;
}
/* 在链表尾部插入节点 */
ListNode *insert(ListNode *head, int val) {
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
if (head == NULL) {
return node;
}
ListNode *p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = node;
return head;
}
/* 在链表中间插入节点 */
ListNode *insert(ListNode *head, int val, int index) {
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
if (head == NULL || index == 0) {
node->next = head;
return node;
}
ListNode *p = head;
int i = 0;
while (p != NULL && i < index - 1) {
p = p->next;
i++;
}
if (p == NULL) {
return head;
}
node->next = p->next;
p->next = node;
return head;
}
```
单链表删除:
```
/* 删除链表头部节点 */
ListNode *delete(ListNode *head) {
if (head == NULL) {
return NULL;
}
ListNode *p = head->next;
free(head);
return p;
}
/* 删除链表尾部节点 */
ListNode *delete(ListNode *head) {
if (head == NULL) {
return NULL;
}
if (head->next == NULL) {
free(head);
return NULL;
}
ListNode *p = head;
while (p->next->next != NULL) {
p = p->next;
}
free(p->next);
p->next = NULL;
return head;
}
/* 删除链表中间节点 */
ListNode *delete(ListNode *head, int index) {
if (head == NULL || index < 0) {
return head;
}
if (index == 0) {
ListNode *p = head->next;
free(head);
return p;
}
ListNode *p = head;
int i = 0;
while (p->next != NULL && i < index - 1) {
p = p->next;
i++;
}
if (p->next == NULL) {
return head;
}
ListNode *q = p->next;
p->next = q->next;
free(q);
return head;
}
```
我希望以上代码能够帮到你,如果你有任何其它问题,请随时问我!
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)