题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
// 反转链表函数
struct ListNode* ReverseList(struct ListNode* head) {
struct ListNode *prev = NULL, *curr = head, *next = NULL;
while (curr != NULL) {
next = curr->next; // 保存当前节点的下一个节点
curr->next = prev; // 反转当前节点的指针方向
prev = curr; // 将当前节点移动到前一个节点
curr = next; // 将当前节点移动到下一个节点
}
return prev; // 返回反转后的链表头节点
}
// 创建链表函数
struct ListNode* createList(int arr[], int n) {
struct ListNode *head = NULL, *tail = NULL;
for (int i = 0; i < n; i++) {
struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = arr[i];
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
// 打印链表函数
void printList(struct ListNode* head) {
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
/**本人思路:
这个代码中,reverseList函数实现了链表反转的功能,它使用三个指针prev、curr和next来记录前一个节点、当前节点和下一个节点。在每次循环中,将当前节点的指针方向反转,然后将指针向前移动一步。最后返回反转后的链表的头节点。这个函数的时间复杂度为O(n),空间复杂度为O(1)。:**/
#华为开奖那些事#
联想公司福利 1500人发布
查看17道真题和解析