#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct node
{
int data;
struct node *next;
};
struct node *top;
int count=0;
void push(int n);
void Print();
void permute();
int main()
{
int no, ch, e;
printf("n1 - Push");
printf("n4 - Print");
printf("n7 - Permute first and last element");
while (1)
{
printf("n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 4:
Print();
break;
case 7:
permute();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}
void push(int no)
{
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp->data=no;
temp->next=top;
top=temp;
count++;
}
void Print()
{
struct node *temp=top;
printf("List is:");
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("n");
}
void permute()
{
int i;
struct node *temp=(struct node*)malloc(sizeof(struct node));
struct node *temp1=(struct node*)malloc(sizeof(struct node));
struct node *temp2=(struct node*)malloc(sizeof(struct node));
temp=top;
temp1=NULL;
for(i=0;i<count-1;i++)
{
temp1=temp1->next;
}
temp1->next=temp2;
temp2->data=temp1->next->data;
temp1->next=temp;
temp->data=top->data;
temp=NULL;
temp2->next=top;
top=temp2;
}
因此,我的堆栈实现可以很好地推送和打印堆栈中的元素,但是当我想用顶部元素排列底部元素时,程序崩溃了。我想我在排列函数中搞砸了一些东西。感谢您事先提供的任何帮助。
如果我正确理解,只需交换两个节点的数据成员data
的值就足够了。函数可以通过以下方式定义
void permute()
{
if ( top && top->next )
{
int data = top->data;
struct node *last = top->next;
while ( last->next ) last = last->next;
top->data = last->data;
last->data = data;
}
}
如果您希望排列节点,这里有一个解决方案。由于执行排列时堆栈中没有新节点,因此无需分配内存。它只是指针处理。
请注意用于处理空堆栈或具有单个元素的堆栈情况的其他测试。
A 删除了 push()
中 malloc()
的返回转换,并测试了 malloc()
的返回值。 如果没有足够的可用内存,malloc()
可能会失败。
以下代码由gcc main.c -o main -Wall
编译:
#include <stdio.h>
#include <stdlib.h>
//#include <conio.h>
struct node
{
int data;
struct node *next;
};
struct node *top;
int count=0;
void push(int n);
void Print();
void permute();
int main()
{
int no, ch;
printf("n1 - Push");
printf("n4 - Print");
printf("n7 - Permute first and last element");
while (1)
{
printf("n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 4:
Print();
break;
case 7:
permute();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}
void push(int no)
{
struct node *temp=malloc(sizeof(struct node));
if(temp==NULL){printf("malloc failedn");exit(1);}
temp->data=no;
temp->next=top;
top=temp;
count++;
}
void Print()
{
struct node *temp=top;
printf("List is:");
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("n");
}
void permute()
{
if(count<2){return;}
int i;
struct node *temp1=top;
struct node *temp2;
for(i=0;i<count-2;i++)
{
temp1=temp1->next;
}
temp2=temp1->next;
temp1->next=top;
temp2->next=top->next;
top->next=NULL;
top=temp2;
}