fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct Node{
  5. int data;
  6. Node* pNext;
  7. };
  8.  
  9. void insertAtBeginning(Node* &pHead, int x);
  10. void insertAfterK(Node* pHead, int x, int k);
  11. void insertBeforeK(Node* &pHead, int x, int k);
  12.  
  13. //-----------------------------------------------------//
  14.  
  15. void insertAtBeginning(Node* &pHead, int x) {
  16. Node* newNode = new Node;
  17. newNode->data = x;
  18. newNode->pNext = pHead;
  19. pHead = newNode;
  20. }
  21.  
  22. //-----------------------------------------------------//
  23.  
  24. void insertAfterK(Node* pHead, int x, int k) {
  25. while(pHead != nullptr && pHead->data != k)
  26. pHead = pHead->pNext;
  27.  
  28. if(pHead == nullptr) return;
  29.  
  30. Node* newNode = new Node;
  31. newNode->data = x;
  32. newNode->pNext = pHead->pNext;
  33. pHead->pNext = newNode;
  34. }
  35.  
  36. //-----------------------------------------------------//
  37.  
  38. void insertBeforeK(Node*& pHead, int x, int k) {
  39. if(!pHead) return;
  40.  
  41. Node* cur = pHead;
  42. if(cur->data == k) {
  43. insertAtBeginning(pHead, x);
  44. return;
  45. }
  46.  
  47. while(cur && cur->pNext && cur->pNext->data != k) {
  48. cur = cur->pNext;
  49. }
  50.  
  51. if(!cur->pNext) return;
  52.  
  53. Node* newNode = new Node;
  54. newNode->data = x;
  55. newNode->pNext = cur->pNext;
  56. cur->pNext = newNode;
  57. }
  58.  
  59. //-----------------------------------------------------//
  60.  
  61. int main() {}
Success #stdin #stdout 0.01s 5424KB
stdin
Standard input is empty
stdout
Standard output is empty