当前位置:   article > 正文

考研数据结构:链表基础算法题满分训练_考研链表模拟题

考研链表模拟题

(1)剑指Offer 从尾到头打印链表

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. vector<int> printListReversingly(ListNode* head) {
  12. vector<int> res;
  13. while(head)
  14. {
  15. res.push_back(head->val);
  16. head = head->next;
  17. }
  18. reverse(res.begin(), res.end());
  19. //return vector<int>(res.rbegin(), res.rend());
  20. return res;
  21. }
  22. };

(2)剑指Offer 在O(1)时间删除链表结点(假设链表一定存在,并且该节点一定不是尾节点。) 

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. void deleteNode(ListNode* node) {
  12. node->val = node->next->val;
  13. node->next = node->next->next;
  14. }
  15. };

(3)剑指Offer 链表中倒数第k个节点 

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode* findKthToTail(ListNode* head, int k) {
  12. int n = 0;
  13. for (ListNode* p = head; p; p = p->next) n ++ ;
  14. if(k > n) return NULL;
  15. ListNode* p = head;
  16. for (int i = 0; i < n - k; i ++ ) p = p->next;
  17. return p;
  18. }
  19. };

 (4)剑指Offer, 语法题, Hulu面试题 反转链表

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode* reverseList(ListNode* head) {
  12. if(!head || !head->next) return head;
  13. ListNode* a = head, *b = a->next;
  14. while(b)
  15. {
  16. ListNode *c = b->next;
  17. b->next = a;
  18. a = b;
  19. b = c;
  20. }
  21. head->next = NULL;
  22. return a;
  23. }
  24. };

(5)剑指Offer 合并两个排序的链表 

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode* merge(ListNode* l1, ListNode* l2) {
  12. ListNode* dummy = new ListNode(-1);
  13. ListNode* tail = dummy;
  14. while(l1 && l2)
  15. {
  16. if(l1->val <= l2->val)
  17. {
  18. tail = tail->next = l1;
  19. l1 = l1->next;
  20. }
  21. else
  22. {
  23. tail = tail->next = l2;
  24. l2 = l2->next;
  25. }
  26. }
  27. if(l1) tail->next = l1;
  28. if(l2) tail->next = l2;
  29. return dummy->next;
  30. }
  31. };

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/615601
推荐阅读
相关标签
  

闽ICP备14008679号