今天看到面试题里面有个链表翻转程序,一时兴起写了一个,第一次竟没得到正确结果,调了半天才出来,稍有惭愧。
#include
<
stdio.h
>
#include < stdlib.h >
struct Node ... {
int data;
struct Node* next;
} ;
void orderinsert(Node *& head, Node *& n) ... {
Node* t=head;
Node* pre=NULL;
while (t && t->data<=n->data)
...{
pre=t;
t=t->next;
}
if(pre)
pre->next=n;
else
head=n;
n->next=t;
}
void sort(Node *& head) ... {
Node* t=head;
Node* h=NULL;
Node* x=NULL;
while (t)
...{
x=t->next;
orderinsert(h,t);
t=x;
}
head=h;
}
void reverse(Node *& head) ... {
Node* pre=NULL;
Node* n=NULL;
Node* t=head;
while (t->next)
...{
n=t->next;
t->next=pre;
pre=t;
t=n;
}
t->next=pre;
head=t;
}
void printlist(Node * p) ... {
printf("list is: ");
while (p)
...{
printf("%d ",p->data);
if(p->next)
p=p->next;
else
break;
}
printf(" ");
}
void main() ... {
int linklen=0;
Node* head=NULL;
Node* tail=NULL;
Node* p=NULL;
printf("input ink length: ");
scanf("%d",&linklen);
if (linklen<=0)
...{
printf("error length.");
return;
}
for(int i=0;i<linklen;i++)
...{
p=(Node*)malloc(sizeof(Node));
p->next=NULL;
printf("input num %d data ",i);
scanf("%d",&(p->data));
//按顺序插入
orderinsert(head,p);
}
printlist(head);
//翻转
reverse(head);
printlist(head);
//再次从小到大排序
sort(head);
printlist(head);
} ;
#include < stdlib.h >
struct Node ... {
int data;
struct Node* next;
} ;
void orderinsert(Node *& head, Node *& n) ... {
Node* t=head;
Node* pre=NULL;
while (t && t->data<=n->data)
...{
pre=t;
t=t->next;
}
if(pre)
pre->next=n;
else
head=n;
n->next=t;
}
void sort(Node *& head) ... {
Node* t=head;
Node* h=NULL;
Node* x=NULL;
while (t)
...{
x=t->next;
orderinsert(h,t);
t=x;
}
head=h;
}
void reverse(Node *& head) ... {
Node* pre=NULL;
Node* n=NULL;
Node* t=head;
while (t->next)
...{
n=t->next;
t->next=pre;
pre=t;
t=n;
}
t->next=pre;
head=t;
}
void printlist(Node * p) ... {
printf("list is: ");
while (p)
...{
printf("%d ",p->data);
if(p->next)
p=p->next;
else
break;
}
printf(" ");
}
void main() ... {
int linklen=0;
Node* head=NULL;
Node* tail=NULL;
Node* p=NULL;
printf("input ink length: ");
scanf("%d",&linklen);
if (linklen<=0)
...{
printf("error length.");
return;
}
for(int i=0;i<linklen;i++)
...{
p=(Node*)malloc(sizeof(Node));
p->next=NULL;
printf("input num %d data ",i);
scanf("%d",&(p->data));
//按顺序插入
orderinsert(head,p);
}
printlist(head);
//翻转
reverse(head);
printlist(head);
//再次从小到大排序
sort(head);
printlist(head);
} ;