单链表构建
1、代码实现:
代码中包含了链表的基本操作,构建以及增删改查:
1、链表的创建包含头插法和尾插法;
2、指定元素删除(修改可以直接调用此函数,实现过程相似);
3、链表的遍历。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
typedef struct Node{
int val;
struct Node *next;
}ListNode;
//使用尾插法创建一个带头结点的链表;
ListNode *create_list_tail(ListNode* l1, int num){
l1 = (ListNode *)malloc(sizeof(ListNode));
l1->next = NULL;
ListNode *temp = NULL, *p = l1;
for(int i = num; i--;i>=0)
{
temp = (ListNode *)malloc(sizeof(ListNode));
temp->val = i;
p->next = temp;
p = temp;
}
p->next = NULL;
return l1;
}
//使用头插法创建一个带头结点的链表;
ListNode *create_list_head(ListNode* l2, int num){
l2 = (ListNode *)malloc(sizeof(ListNode));
l2->next = NULL;
ListNode *temp = NULL, *p = l2;
for(int i = num; i--;i>=0){
temp = (ListNode *)malloc(sizeof(ListNode));
temp->val = i;
temp->next = p->next;
p->next = temp;
}
return l2;
}
//删除指定数字
ListNode *delete_list(ListNode* l3, int target){
ListNode *temp, *pre;
pre = l3;
temp = pre->next;
while(temp->next != NULL){
if(temp->val == target){
pre->next = temp->next;
break;
}
pre = pre->next;
temp = temp->next;
}
return l3;
}
int main()
{
ListNode *list_head, *list_tail, *del_list,*head, *tail;
list_tail = create_list_tail(list_tail,11);
list_head = create_list_head(list_head,11);
head = list_head->next;
printf("头插法输出1-10:\n");
while(head){
printf("%d\t", head->val);
head = head->next;
}
printf("\n尾插法输出1-10:\n");
tail = list_tail->next;
while(tail){
printf("%d\t", tail->val);
tail = tail->next;
}
del_list = delete_list(list_head, 4);
printf("\n删除数字4后的链表:\n");
tail = del_list->next;
while(tail){
printf("%d\t", tail->val);
tail = tail->next;
}
return 0;
}