栈先入后出,链表从投开始遍历;所以如栈然后再依次出栈就完成了逆置;
现写的,没有测试,不过应该没问题:
#define int ElemType
typedef struct Node{
ElemType data;
Node *next;
}Node, *List;
List reverseList(List head)
{
assert(head);
if (head->next == NULL) //如果链表长度为1,就不需要利用栈了
return head;
stack listS;
//从头开始入栈
while (head != NULL)
{
listS.push(head);
head = head->next;
}
//出栈
List pHead = listS.top(); //保存头节点
List pre = NULL , cur = NULL; //当前节点和前一个节点
while(listS.size())
{
//如果是第一个节点
if (pre == NULL){
pre = listS.top();
listS.pop();
}
//不是第一个节点
else{
cur = listS.top();
pre->next = cur;
pre = cur;
listS.top();
}
}
pre ->next = NULL; //置尾结点的下一个节点为NULL;
return pHead;
}
应该是实现单链表反转吧。
把一个链表的所有元素依次push到stack中
然后每次pop两个元素,修改指针的指向,注意到最后队列为空的时候要对头部做一些特殊的处理如:指向空。
#include
struct node{
int data;
struct node *next;
};
typedef struct node stack_node;
typedef stack_node *link;
link stack=NULL;
void push(int data){
link newnode;
newnode=(link)malloc(sizeof(stack_node));
newnode->data=data;
newnode->next=stack;
stack=newnode;
}
int pop(){
link top;
int temp;
if(stack!=NULL){
top=stack;
stack=stack->next;
temp=top->data;
free(top);
return temp;
}
else
return -1;
}
main(){
int i,random,out,value;
int a[20];
i=0;
printf("输入需要逆序的序列,按0结束输入\n");
scanf("%d",&value);
push(value);
while(value){
i++;
scanf("%d",&value);
push(value);
}
for(out=0;outrandom=pop();
printf("%d",random);
}
}
楼上已经回答了