链表的创建和输出
#include<stdio.h>
#include<stdlib.h>
typedef struct snode{
int data;
struct snode *next;
}node;
node *creatlist(int n);
void display(node *head);
int main(){
int n=0;
node *head=NULL;
printf("please enter the number");
scanf("%d",&n);
head=creatlist(n);
display(head);
return 0;
}
node *creatlist(int n){
int i=0;
node *head=NULL;
node *temp=NULL;
node *p=NULL;
for(i=0;i<n;i++){
temp=(node *)malloc(sizeof(struct snode));
scanf("%d",&(temp->data));
temp->next=NULL;
if(head==NULL){
head=temp;
p=temp;
}
else
{
p->next=temp;
p=temp;
}
}
return head;
}
void display(node *head){
node *p=head;
while(p!=NULL){
printf("%d->",p->data);
p=p->next;
}
}
链表的插入和逆转
#include<stdio.h>
#include<stdlib.h>
typedef struct snode{
int data;
struct snode *next;
}node;
node *creatlist(int n);
void display(node *head);
void insertnode(node *head,int data,int pos);
void delete(node *head,int pos);
node *reverse1(node *head);
void printbackward(node *head);
int main(){
int n=0;
node *head=NULL;
printf("please enter the number");
scanf("%d",&n);
head=creatlist(n);
display(head);
printf("after inserting:");
insertnode(head, 8, 3);
display(head);
printf("after delete:");
delete(head,3);
display(head);
printf("after reversed:");
reverse1(head);
display(head);
printbackward(head);
display(head);
return 0;
}
node *creatlist(int n){
int i=0;
node *head=NULL;
node *temp=NULL;
node *p=NULL;
for(i=0;i<n;i++){
temp=(node *)malloc(sizeof(struct snode));
scanf("%d",&(temp->data));
temp->next=NULL;
if(head==NULL){
head=temp;
p=temp;
}
else
{
p->next=temp;
p=temp;
}
}
return head;
}
void display(node *head){
node *p=head;
while(p!=NULL){
printf("%d->",p->data);
p=p->next;
}
printf("\n");
}
void insertnode(node *head,int data,int pos){
node *p=head;
node *temp=(node *)malloc(sizeof(struct snode));
temp->data=data;
int i=1;
while(i<pos){
if(!p->next){
return;
}
p=p->next;
i++;
}
temp->next=p->next;
p->next=temp;
}
void delete(node *head,int pos){
if(pos<=0){
return;
}
node *p=head;
node *temp=(node *)malloc(sizeof(struct snode));
int i=0;
while(i<pos-1){
p=p->next;
i++;
}
temp=p->next;
p->next=temp->next;
free(temp);
}
node *reverse1(node *head){
if(head==NULL||head->next==NULL){
return head;
}else{
node *p=reverse1(head->next);
head->next->next=head;
head->next=NULL;
return p;
}
}
node *reverse2(node *head){
if(head==NULL||head->next==NULL){
return head;
}
node *pre=NULL;
node *aft=head;
node *temp=NULL;
while(aft!=NULL){
temp=aft->next;
aft->next=pre;
pre=aft;
aft=temp;
}
return pre;
}
void printbackward(node *head){
if(head==NULL|| head->next==NULL){
return;
}
printbackward(head->next);
printf("%d->",head->data);
}