请教 每k个节点一组反转链表
同样的两段代码,为什么第一个可以AC,而第二个会报错
#include<iostream> #include<vector> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x):val(x),next(nullptr){} }; ListNode* creatList(vector<int> myVec) { ListNode* pHead=new ListNode(myVec[0]); ListNode* prev = pHead; for(int i=1;i<myVec.size()-1;i++) { pHead->next = new ListNode(myVec[i]); pHead=pHead->next; } return prev; } ListNode* reverseList(ListNode* pHead,int k) { ListNode* right = pHead; ListNode* left = pHead; ListNode* prev = pHead; for(int i=0;i<k;i++) { if(right!=nullptr) right = right->next; else return left; } ListNode* head = left; while(left!=right) { ListNode* pNext = left->next; left ->next = prev; prev = left; left = pNext; } head->next = reverseList(right,k); return prev; } int main() { vector<int> myVec; int temp=0; while(cin>>temp) myVec.push_back(temp); int k=myVec[myVec.size()-1]; ListNode* pHead = creatList(myVec); pHead = reverseList(pHead, k); while(pHead!=nullptr) { cout<<pHead->val<<" "; pHead=pHead->next; } return 0; }
#include<iostream> #include<vector> using namespace std; struct ListNode{ int val; ListNode* next; ListNode(int x):val(x), next(nullptr){} }; ListNode* creatlist(vector<int> num){ ListNode* pHead = new ListNode(num[0]); ListNode* pre = pHead; for(int i = 1;i < num.size()-1;i++){ pre->next = new ListNode(num[i]); pre = pre->next; } return pHead; } ListNode* reverselist(ListNode* pHead, int k){ ListNode* right = pHead; ListNode* left = pHead; ListNode* pre = pHead; for(int i = 0;i < k;i++){ if(right != nullptr) right = right-> next; else return left; } ListNode* head = left; while(left != right){ ListNode* next= left->next; left->next = pre; pre = left; left = next; } head->next = reverselist(right, k); return pre; } int mian(){ vector<int> num; int n =0; while(cin >> n){ num.push_back(n); } int k = num[num.size()-1]; ListNode* pNode= creatlist(num); ListNode* res = reverselist(pNode,k); while(res != nullptr){ cout << res->val << " "; res= res->next; } return 0; }报错信息如下
warning: comparison of integers of different signs: 'int' and 'unsigned long' [-Wsign-compare]
for(int i = 1;i < num.size()-1;i++){
求大佬帮忙解答一下