⭐️ 往期相关文章
✨链接:数据结构-手撕单链表+代码详解。
⭐️ 题目描述
🌟 leetcode链接:反转链表
1️⃣ 代码:
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*//*思路1:把所给链表依次头插
*/
struct ListNode* reverseList(struct ListNode* head){// 新的头结点struct ListNode* newHead = NULL;// 遍历链表struct ListNode* cur = head;while (cur != NULL) {// 记录下一个位置struct ListNode* next = cur->next;// 头插cur->next = newHead;newHead = cur;//迭代cur = next;}return newHead;
}
2️⃣ 代码:
/*思路2:改变链表的指向
*/
struct ListNode* reverseList(struct ListNode* head){// 链表为空if (head == NULL)return NULL;struct ListNode* prev = NULL;struct ListNode* cur = head;// 特殊情况:cur 为 NULL。 error:NULL->nextstruct ListNode* next = cur->next;while (cur != NULL) {// 改变链表的指向cur->next = prev;// 迭代prev = cur;cur = next;// 特殊情况:next = NULL if (next != NULL) next = next->next;}return prev;
}