用C++语言创建单链表的声明,初始化,读取,插入,删除,修改功能
时间: 2024-06-06 13:08:54 浏览: 42
好的,关于创建单链表的声明,初始化,读取,插入,删除以及修改功能,在C语言中可以这样实现:
声明:
typedef struct Node{
int data;
struct Node* next;
} ListNode;
初始化:
ListNode * createList(){
ListNode *head;
head = (ListNode *)malloc(sizeof(ListNode));
head->next = NULL;
return head;
}
读取:
void readList(ListNode *head){
ListNode *p = head->next;
while(p != NULL){
printf("%d ",p->data);
p = p->next;
}
}
插入:
void insertList(ListNode *head,int pos,int num){
ListNode *p = head;
for(int i=0;i<pos-1;i++){
p = p->next;
}
ListNode *newNode;
newNode = (ListNode *)malloc(sizeof(ListNode));
newNode->data = num;
newNode->next = p->next;
p->next = newNode;
}
删除:
void deleteList(ListNode *head,int pos){
ListNode *p = head;
for(int i=0;i<pos-1;i++){
p = p->next;
}
ListNode *temp = p->next;
p->next = temp->next;
free(temp);
}
修改:
void changeList(ListNode *head,int pos,int num){
ListNode *p = head;
for(int i=0;i<pos;i++){
p = p->next;
}
p->data = num;
}
如有不理解的地方,欢迎继续交流。
阅读全文