ListNode* buildList(int* arr,int n) { ListNode *head=new ListNode,*val,*cul=*head; for(int j=0;j<n;j++){ val=new ListNode; cul->next=val; cul->ListNode(*(arr+i)); cul=val; } return head; } ListNode* reverse(head) { ListNode* hh,*left=head,*right; hh=head->next; right=hh->next; hh->next=NULL; while(right!=NULL){ left=hh; hh=right; right=rigth->next; hh->next=left; } return hh; } void printList(head) { while(head!=NULL){ cout<<head->val<<' '; head=head->next; } } 这段代码错在哪里,怎么改
时间: 2024-01-19 12:04:55 浏览: 17
这段代码有以下几个问题:
1. 在 `buildList` 函数中,第一个节点没有被初始化,即 `head->val` 没有被赋值。应该将 `head` 初始化为 `NULL`,并在循环内部创建新节点并赋值。
2. 在 `buildList` 函数中,第 8 行的 `cul->ListNode(*(arr+i))` 是无意义的,应该将其改为 `cul->val = *(arr + j)`。
3. 在 `reverse` 函数中,第 2 行应该指定 `head` 的类型为 `ListNode*`,即 `ListNode* reverse(ListNode* head)`。
4. 在 `reverse` 函数中,第 4 行的 `right=rigth->next` 中的 `rigth` 拼写错误,应该改为 `right=right->next`。
下面是修改后的代码:
```
ListNode* buildList(int* arr, int n) {
ListNode* head = NULL;
ListNode *val, *cul = head;
for (int j = 0; j < n; j++) {
val = new ListNode;
val->val = *(arr + j);
if (cul == NULL) {
head = val;
cul = val;
} else {
cul->next = val;
cul = val;
}
}
return head;
}
ListNode* reverse(ListNode* head) {
ListNode *hh, *left = head, *right;
hh = head->next;
right = hh->next;
hh->next = NULL;
while (right != NULL) {
left = hh;
hh = right;
right = right->next;
hh->next = left;
}
return hh;
}
void printList(ListNode* head) {
while (head != NULL) {
cout << head->val << ' ';
head = head->next;
}
}
```