69,335
社区成员
发帖
与我相关
我的任务
分享
/****************另一个倒置***************************/
void reverse(NODE * head)
{
NODE *p,*q,*r;
p=NULL;
q=head->next;
while(q)
{
r=q->next;
q->next=p;
p=q;
q=r;
}
head->next=p;
}
/*******************倒置函数***********************/
void ds(NODE *head)
{
NODE *p;
p=head;
struct stack s;
init(&s);
printf("Begin to ds the LinkList...\n");
while (p->next!=NULL)
{
push(&s,p->next->data);
p=p->next;
}
p=head;
while (!empty(&s))
{
p->next->data=pop(&s);
p=p->next;
}
printf("\nThe dsList ended!\n");
}
#include <stdio.h>
#include <malloc.h>
typedef struct node{
int data;
struct node *next;
} NODE;
//********************链表**********************/
NODE *Create(){
NODE *p,*head;
int x;
head=(NODE *)malloc(sizeof(NODE));
head->next=NULL;
printf("Input data,-1 to End!\n");
scanf("%d",&x);
while(x!=-1){
p=(NODE *)malloc(sizeof(NODE));
p->data=x;
p->next=head->next;
head->next=p;
scanf("%d",&x);
}
return(head);
}
/******************************************/
void Output(NODE *head){
NODE *p;
p=head;
printf("Begin to dump the LinkList...\n");
while(p->next!=NULL){
printf("->%d",p->next->data);
p=p->next;
}
printf("\nThe LinkList ended!\n");
}
/*******************倒置函数***********************/
NODE* ds(NODE *head){
NODE *p,*p1,*p2=NULL;
p=head;
printf("Begin to ds the LinkList...\n");
p=p->next;
while(p!=NULL)
{
p1=p;
p=p->next;
p1->next=p2;
p2=p1;
}
head->next=p2;
printf("\nThe dsList ended!\n");
return head;
}
/******************************************/
void main(){
NODE *head;
head=Create();
Output(head);
ds(head);
Output(head);
}
你要的结果:
Input data,-1 to End!
2 5 9 1 3 -1
Begin to dump the LinkList...
->3->1->9->5->2
The LinkList ended!
Begin to ds the LinkList...
The dsList ended!
Begin to dump the LinkList...
->2->5->9->1->3
The LinkList ended!
Press any key to continue . . .
pNode Reverse(pNode head){
// 防止传入为空链表
if ( head == NULL) return NULL;
// 预处理
pNode p=new Node;
p = head->next;
head->next = NULL;
// 交换前后..用p表示未交换头..head反转后存储
while (p != NULL)
{
swap(p->next, head);
swap(head, p);
}
delete p;
p=NULL;
// 实现链式操作
return head;
}