oppo笔试题编程二重排链表
第二题死活只能a 60,输入输出都是处理好的,应该不是输入的错误数据
有一说一 这道题ACM模式有点难受 输入格式 head = [1,2,3,4,5]
在LeetCode能ac
求大佬指点下
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int v):val(v),next(NULL){}
};
ListNode* reverseList(ListNode *head)
{
ListNode *cur = head, *pre = NULL, *nxt =NULL;
while(cur)
{
nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
void helper(ListNode * head)
{
//快慢指针
ListNode *slow=head,*fast=head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
}
ListNode *newNode = slow->next;
slow->next=NULL;
ListNode *newHead = reverseList(newNode);
ListNode *cur=head,*nxt=NULL,*p=newHead,*pnxt=NULL;
while(p)
{
pnxt = p->next;
nxt = cur->next;
cur->next = p;
p->next = nxt;
cur = nxt;
p = pnxt;
}
ListNode *res =head;
cout<<"[";
while(res->next)
{
cout<<res->val<<",";
res=res->next;
}
cout<<res->val<<"]";
}
int main()
{
string str;
getline(cin, str);
int n = str.size();
string strlist = str.substr(8,n-9);
//建立链表
if(strlist.empty())
{
cout<<"error"<<endl;
return 0;
}
if(strlist.size()==1)
{
cout<<"["<<strlist[0]<<"]";
return 0;
}
stringstream ss(strlist);
string p;
ListNode *dummy = new ListNode(-1);
ListNode *pp = dummy;
while(getline(ss,p,','))
{
int num = stoi(p);
ListNode *numNode = new ListNode(num);
//cout<<numNode->val<<endl;
pp->next = numNode;
pp = numNode;
}
ListNode *head=dummy->next;
ListNode *res =head;
//head = [1,2,3,4,5,6]
helper(head);
return 0;
}
查看10道真题和解析
