好久没接触链表了,今天做凤姐的作业,发现什么都不会了,数据结构作业真烦,书上的都是伪代码,都不能用,书名还叫<数据结构(C语言版)>,还是<数据结构(伪代码版)>更合适吧….
第一道题是单链表就地逆置,第一学期接触过,
第二道题是删除单链表(已排好序)中大于mink小于maxk的数,应该也很简单,不过一写代码发现连怎么定义结构体都忘了..网上开始找,东拼西凑在自己加一点,终于编译通过了.
这里把2个题目合起来,凑成一个完整的C语言代码:
#include <malloc.h>
#define LEN sizeof(struct node)
struct node /*定义结构体*/
{
int data;
struct node* next;
};//
struct node* creatlist()/*单指针建立带头结点的单链表*/
{
struct node* head;/*声明头指针*/
struct node* p;
head=(struct node*)malloc(LEN);
head->next=NULL;
p=(struct node*)malloc(LEN);
printf("input the num:\n");
scanf("%d",&p->data);
while(p->data){//输入0停止
p->next=head->next;
head->next=p;
p=(struct node*)malloc(LEN);
scanf("%d",&p->data);
}
free(p);
return head;
}
void printlist(struct node*head)//显示data
{
struct node* p;
p=head->next;
while(p){
printf("%d ",p->data);
p=p->next;
}
}
void reverse(struct node*head)//单链表的就地逆置
{
struct node* p,* q;
p=head->next;
while(p->next!=NULL)
{
q= p->next;
p->next=q->next; //删除结点q,但未释放
q->next=head->next;
head->next=q; //将q插入头结点之后
}
}
void delete_between(struct node*head,int mink,int maxk)//删除链表中大于mink小于maxk的数
{
struct node* p,* q;
p=head;
while(p->next->data<=mink)
p=p->next;
if(p->next)
{
q=p->next;
while(q->data<maxk)
{
p->next=q->next;
free(q);
q=p->next;
}
}
}
int main()
{
struct node* head;
head=creatlist();
printlist(head);
reverse(head);
printf("\n");
printlist(head);
delete_between(head,2,4);
printf("\n");
printlist(head);
return 0;
}
by 异泪
顶,my brother
异弟好……
comment5,
comment6,
Couldnt agree more with that, very attractive article
Thanks!