给定一个单链表的头结点 pHead(该头节点是有值的,比如在下图,它的 val 是 1),长度为 n,反转该链表后,返回新链表的表头。 数据范围: 0≤n≤1000 要求:空间复杂度 O(1) ,时间复杂度 O(n) 如当输入链表{1,2,3}时,经反转后,原链表变为{3,2,1},所以对应的输出 为{3,2,1}。 示例:输入{1,2,3} 返回{3,2,1}请给出可运行的c语言代码
时间: 2023-05-15 20:05:21 浏览: 163
带头结点的单链表,反转并输出
以下是可运行的C语言代码:
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode *prev = NULL;
struct ListNode *curr = head;
while (curr != NULL) {
struct ListNode *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
// 示例代码
int main() {
struct ListNode *pHead = (struct ListNode*)malloc(sizeof(struct ListNode));
pHead->val = 1;
pHead->next = (struct ListNode*)malloc(sizeof(struct ListNode));
pHead->next->val = 2;
pHead->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
pHead->next->next->val = 3;
pHead->next->next->next = NULL;
struct ListNode *newHead = reverseList(pHead);
while (newHead != NULL) {
printf("%d ", newHead->val);
newHead = newHead->next;
}
printf("\n");
return 0;
}
阅读全文