LeetCode--链表3-经典问题
题1 反转链表
第一次代码超出时间限制
原因是,反转之后链表的尾部节点和头结点连上了
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { // 如果头节点为空 if(!head) return NULL; // 如果链表中只有一个节点 if(!head->next) return head; // ListNode* cur = head; ListNode* pre = nullptr; while( cur ) { ListNode* tmp = cur->next; cur->next = pre; pre = cur; cur = tmp; } return pre; } };
题2 合并两个有序链表
通过测试:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { // 如果有一个链表为空就返回另一个 if(!l1) return l2; if(!l2) return l1; // 创建一个新的链表指针 ListNode* p1 = l1; ListNode* p2 = l2; ListNode* head; if(p1->val >= p2->val) { head = p2; p2 = p2->next; }else{ head = p1; p1 = p1->next; } ListNode* p = head; // p1和p2都不为空的时候开始拼接 while( p1 != nullptr && p2 != nullptr ) { if( p1->val >= p2->val) { p->next = p2; p2 = p2->next; }else{ p->next = p1; p1 = p1->next; } p = p->next; } if(!p2) { p->next = p1; } if(!p1) { p->next = p2; } return head; } };
题3 删除链表中的节点
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void deleteNode(ListNode* node) { if( node->next == nullptr ) { node = nullptr; } node->val = node->next->val; node->next = node->next->next; } };
题4 移除链表元素
错误示例,拼接链表的时候一定要注意:指向链表节点的指针可能连着好多个节点
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeElements(ListNode* head, int val) { if( head == nullptr) return NULL; queue<ListNode*> ss; ListNode* p = head; while(p) { if( p->val != val) { ss.push(p); p = p->next; } else{ p = p->next; } } ListNode* ans = ss.front(); ListNode* pp = ans; ss.pop(); ans = ans->next; while(!ss.empty()) { ans = ss.front(); ss.pop(); ans = ans->next; } return pp; } };
来源:https://www.cnblogs.com/jiangxinyu1/p/12285035.html