C语言单链表的基本算法代码
时间: 2023-03-31 15:03:13 浏览: 86
单链表的基本算法代码如下:
//定义单链表结构体
typedef struct ListNode{
int val;
struct ListNode *next;
}ListNode;
//创建单链表
ListNode* createList(int arr[], int n){
ListNode *head = NULL, *tail = NULL;
for(int i = ; i < n; i++){
ListNode *node = (ListNode*)malloc(sizeof(ListNode));
node->val = arr[i];
node->next = NULL;
if(head == NULL){
head = tail = node;
}else{
tail->next = node;
tail = node;
}
}
return head;
}
//遍历单链表
void traverseList(ListNode *head){
ListNode *p = head;
while(p != NULL){
printf("%d ", p->val);
p = p->next;
}
}
//插入节点
ListNode* insertNode(ListNode *head, int val){
ListNode *node = (ListNode*)malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
if(head == NULL){
head = node;
}else{
ListNode *p = head;
while(p->next != NULL){
p = p->next;
}
p->next = node;
}
return head;
}
//删除节点
ListNode* deleteNode(ListNode *head, int val){
if(head == NULL){
return NULL;
}
if(head->val == val){
ListNode *p = head;
head = head->next;
free(p);
return head;
}
ListNode *p = head;
while(p->next != NULL && p->next->val != val){
p = p->next;
}
if(p->next != NULL){
ListNode *q = p->next;
p->next = q->next;
free(q);
}
return head;
}
//反转单链表
ListNode* reverseList(ListNode *head){
ListNode *prev = NULL, *curr = head;
while(curr != NULL){
ListNode *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)