当list不带头节点的时候,如果想要main函数中的链表改变,当为一层指针传入头结点时,调用的函数必须要有返回值。
#include <stdio.h>
#include <malloc.h>
struct node {
int data;
struct node *next;
};
struct node *create(struct node *head, int data){
if(head == NULL){
head = (struct node *)malloc(sizeof(struct node));
head->data = data;
head->next = NULL;
}else{
struct node *p = head;
while(p->next){
p = p->next;
}
struct node *node = (struct node *)malloc(sizeof(struct node));
node->data = data;
node->next = NULL;
p->next = node;
}
return head;
}
void print(struct node *head){
if(head == NULL){
return;
}else{
struct node *p = head;
while(p){
printf("%d", p->data);
p = p->next;
}
printf("\n");
}
}
int main()
{
struct node *head1 = NULL;
int data;
for(int i=0; i<5;i++){
head1 = create(head1,i);
}
print(head1);
return 0;
}
当list带头节点的时候,如果想要main函数中的链表改变,当为一层指针传入头结点时,调用的函数无需返回值。
#include <stdio.h>
#include <malloc.h>
struct node {
int data;
struct node *next;
};
void create(struct node *head, int data){
if(head == NULL){
return ;
}
struct node *p = head;
while(p->next){
p = p->next;
}
struct node *node = (struct node *)malloc(sizeof(struct node));
node->data = data;
node->next = NULL;
p->next = node;
}
void print(struct node *head){
if(head == NULL){
return;
}else{
struct node *p = head->next;
while(p){
printf("%d", p->data);
p = p->next;
}
printf("\n");
}
}
int main()
{
struct node *head1 = (struct node *)malloc(sizeof(struct node));
int data;
for(int i=0; i<5;i++){
create(head1,i);
}
print(head1);
return 0;
}
当list不带头节点的时候,如果想要main函数中的链表改变,当为双层指针指针传入头结点时,调用的函数不需要有返回值。
struct node *delete(struct node *head, int data){
if(head->data == data){
struct node *tmp = head->next;
free(head);
return tmp;
}
struct node *p = head;
struct node *q = head->next;
struct node *tmp;
while(q){
if(q->data == data){
tmp = q;
p->next = tmp->next;
free(q);
return head;
}
p = p->next;
q = q->next;
}
}
void print(struct node *head){
if(head == NULL){
return;
}else{
struct node *p = head;
while(p){
printf("%d", p->data);
p = p->next;
}
printf("\n");
}
}
int main()
{
struct node *head1 = NULL;
struct node *head2 = NULL;
int data;
for(int i=0; i<5;i++){
create(&head1,i);
}
print(head1);
for(int i=2; i<5;i++){
delete(head1,i);
}
print(head1);
return 0;
}