题目描述
输入一个链表,反转链表后,输出新链表的表头。
//运用三个指针实现反转
ListNode* ReverseList(ListNode* pHead){
if(pHead==NULL)return NULL;
if(pHead->next==NULL)return pHead;
ListNode* pre=NULL,*p1=pHead,*p2=pHead->next;
while(1)
{
if(p2==NULL)
{
p1->next=pre;
pHead=p1;
break;
}
else
{
p1->next=pre;
pre=p2->next;
p2->next=p1;
if(pre==NULL)
{
pHead=p2;
break;
}
else
{
p1=pre;
pre=p2;
p2=p1->next;
}
}
}
return pHead;
}
//第一次遍历存储把数据压入栈,第二次遍历,数据出栈,实现反转
ListNode* ReverseList(ListNode* pHead) {
stack<int> stack1;
if(pHead==NULL)return NULL;
else if(pHead->next==NULL)return pHead;
else
{
ListNode* cur=pHead;
while(cur!=NULL)
{
stack1.push(cur->val);
cur=cur->next;
}
cur=pHead;
while(cur!=NULL)
{
cur->val=stack1.top();
stack1.pop();
cur=cur->next;
}
return pHead;
}
}