源代碼
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAXSIZE 100
//定義單鏈表
typedef struct node
{
int data;
struct node *next;
}linklist;
linklist *head;
//定義棧
typedef struct st
{
int d[100];
int top;
}seqstack;
seqstack s1;
//創建單鏈表
linklist *creatlist()
{
linklist *p, *q, *head;
p = q = (linklist *)malloc(sizeof(linklist));
head = p;
p->next = NULL;//定義頭結點,頭結點數據域為空
p = (linklist *)malloc(sizeof(linklist));
scanf("%d", &p->data);
while (p->data != -1)
{
q->next = p;
q = p;
p = (linklist *)malloc(sizeof(linklist));
scanf("%d", &p->data);
}
q->next = NULL;
return head;
}
//輸出單鏈表
void print(linklist *head)
{
linklist *p;
p = head->next;
if (p == NULL)
printf("\n空鏈表!\n");
else
{
do
{
printf("%6d", p->data);
p = p->next;
} while (p != NULL);
printf("\n");
}
}
//初始化棧,構造一個空棧
int InitStack(seqstack *s)
{
s->top = 0;
return 1;
}
//入順序棧
seqstack *Push(seqstack *s, int x)
{
if (s->top == MAXSIZE - 1)
{
printf("\n棧已滿,不能進入棧\n");
return 0;
}
else
{
s->top++;
s->d[s->top] = x;
return s;
}
}
//判斷棧是否為空
int StackEmpty(seqstack *s)
{
if (s->top == 0)
return 1; //棧為空時返回1(真)
else
return 0; //棧非空時返回0(假)
}
//出棧操作
int Pop(seqstack *s)
{
int y;
//if (s->top == 0)
if(StackEmpty(s))
{
printf("\n棧為空,無法出棧!\n");
return 0;
}
else
{
y = s->d[s->top];
s->top--;
return y;
}
}
//利用棧s逆置單鏈表
linklist *back_linklist(linklist *head)
{
linklist *p;
InitStack(&s1);
p = head->next;//p指向首結點
while (p)
{
Push(&s1, p->data); //鏈表結點中的數據入棧
p = p->next; //p指針后移
}
p = head->next;//p再指向首結點
while (!StackEmpty(&s1)) //當棧s不空時
{
p->data = Pop(&s1); //數據出棧,並存入p所指結點的數據域
p = p->next; //p指針后移
}
return head;
}
/*
linklist *reverse_linklist(linklist *head)
{
linklist *p;
InitStack(&s1);
p = head->next;
while (p)
{
Push(&s1, p->data);
if (p->next == NULL)
p = p->next;
else
p = p->next->next;
}
p = head->next;
while (!StackEmpty(&s1))
{
p->data = Pop(&s1);
if (p->next == NULL)
p = p->next;
else
p = p->next->next;
}
return head;
}
*/
int main()
{
linklist *head;
head = creatlist();
print(head);
head = back_linklist(head);
print(head);
// system("pause");
return 1;
}
運行結果: