这题有两种思考方式,一种是添加辅助空间,先进后出,当然是栈了,做法就是遍历链表,将值压入栈中,然后再一次弹出。还有一种方法是链表反序,链表反序也有两种方法。一种是将链表在原有的基础上更改指针,进行反序。光看代码可能不太还理解,我们可以看一下执行过程。
假设p1->p2->p3->p4->p5->p5->.......那么执行一次为p1<-p2->p3->p4->p5.......然后p1=p2;p2=p3;将其更新为新的p1->p2->p3->p4....循环执行,直到p1->p2->p3....这个序列为空。
简化的过程即为:p2->next=p1;p1=p2;p2=p3;
那么我们可以设置三个指针,pre,pnode,pnext进行head->s1->s2->s3->...->null;操作。pre初始化为NULL,pnode=head,pnext=pnode->next;
即为while(pnode!=NULL)
{
pnext=pnode->next;
if(pnext==NULL)head=pnode;
pnode->next=pre;
pre=pnode;
pnode=pnext;
}
上面的if判断条件是指当pnext==NULL时,说明未转换的链表部分只剩下最后一个,我们这时候可以把它做为头,但是这样做的的话需要注意的是,遍历时,头结点也是包含元素的。
除了这种方法还有一个比较笨的方法是在遍历链表的同时使用头插法建立另一个链表,这样也是可以的。具体的话看面试官有什么要求,推荐第一种和第二种,第三种有点笨。
链表本身反序:
#include <stdio.h>
#include <iostream>
#include <stack>
using namespace std;
struct ListNode
{
int mvalue;
ListNode *next;
};
ListNode *Reserve(ListNode* head)
{
ListNode *pre,*pnode,*pnext;
pnode=head;
pre=NULL;
while(pnode!=NULL)
{
pnext=pnode->next;
if(pnext==NULL)head=pnode;
pnode->next=pre;
pre=pnode;
pnode=pnext;
}
return head;
}
int main()
{
//freopen("/Users/sanyinchen/Workspaces/oc/conse/B_ali/B_ali/in.txt","r",stdin);
stack<int> mstack;
ListNode *head=new ListNode();
ListNode *t;
t=head;
int m;
while(scanf("%d",&m)&&m!=-1)
{
ListNode *s=new ListNode();
s->mvalue=m;
t->next=s;
t=s;
}
t->next=NULL;
head=Reserve(head);
while(head->next!=NULL)
{
printf("%d\n",head->mvalue);
head=head->next;
}
return 0;
}
头插法:
#include <stdio.h>
#include <iostream>
#include <stack>
using namespace std;
struct ListNode
{
int mvalue;
ListNode *next;
};
int main()
{
//freopen("/Users/sanyinchen/Workspaces/oc/conse/B_ali/B_ali/in.txt","r",stdin);
stack<int> mstack;
ListNode *head=new ListNode();
ListNode *tail=new ListNode();
ListNode *t;
t=head;
int m;
while(scanf("%d",&m)&&m!=-1)
{
ListNode *s=new ListNode();
s->mvalue=m;
t->next=s;
t=s;
}
t->next=NULL;
tail->next=NULL;
while(head->next!=NULL)
{
head=head->next;
ListNode *s=new ListNode();
s->mvalue=head->mvalue;
s->next=tail->next;
tail->next=s;
}
while(tail->next!=NULL)
{
tail=tail->next;
printf("%d\n",tail->mvalue);
}
return 0;
}
使用栈:
#include <stdio.h>
#include <iostream>
#include <stack>
using namespace std;
struct ListNode
{
int mvalue;
ListNode *next;
};
int main()
{
//freopen("/Users/sanyinchen/Workspaces/oc/conse/B_ali/B_ali/in.txt","r",stdin);
stack<int> mstack;
ListNode *head=new ListNode();
ListNode *t;
t=head;
int m;
while(scanf("%d",&m)&&m!=-1)
{
ListNode *s=new ListNode();
s->mvalue=m;
t->next=s;
t=s;
}
t->next=NULL;
while(head->next!=NULL)
{
head=head->next;
mstack.push(head->mvalue);
}
while(!mstack.empty())
{
printf("%d\n",mstack.top());
mstack.pop();
}
return 0;
}