#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}NODE;
//尾插法
//创建一个带头节点的单链表
NODE *create1(){
NODE *head=(NODE *)malloc(sizeof(NODE));
NODE *p=head,*q;
int n;
scanf("%d",&n);
//输入链表节点数据,直至输入-1结束!
while(n!=-1){
q=(NODE *)malloc(sizeof(NODE));
q->data=n;
p->next=q;
p=q;
scanf("%d",&n);
}
p->next=NULL;
return head;
}
void Print1(NODE *head){
NODE *p=head->next;
while(p!=NULL){
printf("%d,",p->data);
p=p->next;
}
}
//尾插法
//创建一个不带头节点的单链表 这是建立的正序的
NODE *create2(){
NODE *h=(NODE *)malloc(sizeof (NODE));
NODE *p,*q;
int n;
scanf("%d",&n);
h->data=n;
p=h;
scanf("%d",&n);
while(n!=-1){
q=(NODE*)malloc(sizeof(NODE));
q->data=n;
p->next=q;
p=q;
scanf("%d",&n);
}
p->next=NULL;
return h;
}
void Print2(NODE *h){
NODE *p=h;
while(p!=NULL){
printf("%d,",p->data);
p=p->next;
}
}
//头插法
//带头节点 反序的
NODE *create3(){
NODE *head=(NODE *)malloc(sizeof(NODE));
head->next=NULL;
NODE *q;
int n;
scanf("%d",&n);
while(n!=-1){
q=(NODE *)malloc(sizeof(NODE));
q->data=n;
q->next=head->next;
head->next=q;
scanf("%d",&n);
}
return head;
}
//头插法
//不带头节点 反序!要区分第一个节点的情况!
NODE *create4(){
NODE *h=(NODE *)malloc(sizeof (NODE));
h=NULL;
NODE *q;
int n;
scanf("%d",&n);
while(n!=-1){
q=(NODE*)malloc(sizeof(NODE));
q->data=n;
if(h==NULL){
q->next=NULL;
h=q;
}
else{
q->next=h;
h=q;
}
scanf("%d",&n);
}
return h;
}
//NODE *reverse(NODE *&head)
//这种写法对应mian不用新的NODE *p接收这个head
//reverse(head);
//Print2(head);
NODE *reverse(NODE *head){
printf("\nreverse:\n");
if(head==NULL||head->next==NULL) return head;
NODE *p,*q;
q=head->next;
head->next=NULL;
while(q!=NULL){
p=q->next;
q->next=head;
head=q;
q=p;
}
return head;
}
int main(){
NODE *head=create4();
Print2(head);
// NODE *p=reverse(head);
// Print2(p);
return 0;
}
12-08
7082
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-21
4180
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-21
6110
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-12
3417
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-21
2613
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-17
9814
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交