一、在单链表中删除所有值为x的结点,输出删除后的单链表
二、逆置单链表
一、
- delete.c
#include<stdio.h>
#include<stdlib.h>
#include"delete.h"
Node *create()
{
Node *first = NULL;
Node *last = NULL;
element x;
printf("请输入数据,0为结束标志。");
while(1)
{
scanf("%d",&x);
if(x == 0)
{
break;
}
Node *p = (Node *)malloc(sizeof(Node));
p->data = x;
p->next = NULL;
if(first == NULL)
{
first = p;
last = p;
}
else
{
last->next = p;
last = p;
}
}
return first;
}
/*
功能:删除单链表中所有为x的结点
参数:@h:指向第一个结点的指针;@x:要删除的数据
返回值:指向第一个结点的指针
*/
Node *delete(Node *h,element x)
{
Node *p = NULL;
if(h == NULL)
{
return NULL;
}
if(h->data != x)
{
h->next = delete(h->next,x);
return h;
}
else
{
p = h;
h = h->next;
p->next = NULL;
free(p);
return delete(h,x);
}
}
void printlist(Node *first)
{
Node *p = first;
printf("链表中结点的值依次是:\n");
while(p)
{
printf("%d",p->data);
p = p->next;
}
printf("\n");
}
- delete.h
#ifndef __DELETE_H__
#define __DELETE_H__
#define element x
typedef struct node
{
element data;
struct node *next;
}Node;
Node *create();
Node *delete(Node *h,element x);
void printlist(Node *first);
#endif
- main.c
#include<stdio.h>
#include"delete.h"
int main()
{
Node *first = create();
printflist(first);
element x;
printf("请输入要删除的数据:\n");
scanf("%d",&x);
first = delete(first,x);
printflist(first);
return 0;
}
二、原地逆置单链表,即不再重新分配内存空间
- reverse.c
#include<stdio.h>
#include<stdlib.h>
#include"reverse.h"
Node *create()
{
Node *first = NULL;
Node *last = NULL;
element x;
printf("请输入数据,0为结束标志。");
while(1)
{
scanf("%d",&x);
if(x == 0)
{
break;
}
Node *p = (Node *)malloc(sizeof(Node));
p->data = x;
p->next = NULL;
if(first == NULL)
{
first = p;
last = p;
}
else
{
last->next = p;
last = p;
}
}
return first;
}
/*
功能:逆置单链表
参数:@h:指向第一个结点的指针
返回值:指向第一个结点的指针
*/
Node *reverse(Node *h)
{
Node *first = NULL;
Node *p = NULL;
while(h)
{
p = h;
h = h->next;
p->next = NULL;
if(first == NULL)
{
first = p;
}
else
{
p->next = first;
first = p;
}
}
return first;
}
void printlist(Node *first)
{
Node *p = first;
printf("链表中结点的值依次是:\n");
while(p)
{
printf("%d",p->data);
p = p->next;
}
printf("\n");
}
- reverse.h
#ifndef __REVERSE_H__
#define __REVERSE_H__
#define element x;
Node *create();
Node *reverse(Node *h);
void printlist(Node *first);
#endif
- main.c
#include<stdio.h>
#include"reverse.h"
int main()
{
Node *first = create();
printflist(first);
first = reverse(first);
printflist(first);
return 0;
}