fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct Node{
  4. int val;
  5. Node*next;
  6. };
  7. Node*InsertAtBegin(Node*root,int x)
  8. {
  9. Node*newnode=new Node();
  10. newnode->val=x;
  11. newnode->next=NULL;
  12. if(root==NULL)
  13. {
  14. root=newnode;
  15. return root;
  16. }
  17. else
  18. {
  19. newnode->next=root;
  20. root=newnode;
  21. return root;
  22. }
  23. }
  24. Node*DeleteFromBegin(Node*root,int x)
  25. {
  26. if(root==NULL)
  27. return root;
  28. Node*temp=root;
  29. root=root->next;
  30. delete temp;
  31. return root;
  32. }
  33. Node*DeleteFromPos(Node*root,int x,int pos)
  34. {
  35. if(root==NULL || pos<0)
  36. {
  37. return NULL;
  38. }
  39. Node*currnode,*prevnode;
  40. currnode=root;
  41. prevnode=NULL;
  42. int count=0;
  43. while(currnode!=NULL && count<pos)
  44. {
  45. prevnode=currnode;
  46. currnode=currnode->next;
  47. }
  48. if(currnode!=NULL)
  49. {
  50. prevnode->next=currnode->next;
  51. delete currnode;
  52. }
  53. return root;
  54. }
  55. Node*DeleteFromEnd(Node*root,int x)
  56. {
  57. if(root==NULL)
  58. return NULL;
  59. if(root->next==NULL)
  60. return root;
  61. Node*currnode;
  62. currnode=root;
  63. while(currnode->next && currnode->next->next)
  64. {
  65. currnode=currnode->next;
  66. }
  67. Node*temp=currnode->next;
  68. currnode->next=NULL;
  69. delete temp;
  70. return root;
  71. }
  72.  
  73. void Print(Node*root)
  74. {
  75. Node*currnode;
  76. currnode=root;
  77. while(currnode!=NULL)
  78. {
  79. cout<<currnode->val<<"->";
  80. currnode=currnode->next;
  81. }
  82. cout<<endl;
  83. }
  84. int main()
  85. {
  86. Node*root=NULL;
  87. int n;
  88. cin>>n;
  89. if(n<=0)
  90. {
  91. cout<<endl;
  92. return 0;
  93. }
  94. int a[n];
  95. for(int i=0;i<n;i++)
  96. {
  97. cin>>a[i];
  98. }
  99. Print(root);
  100. for(int i=0;i<n;i++)
  101. {
  102. root=InsertAtBegin(root,a[i]);
  103. }
  104. Print(root);
  105. for(int i=0;i<n;i++)
  106. {
  107. root=DeleteFromBegin(root,a[i]);
  108. }
  109. Print(root);
  110. for(int i=0;i<n;i++)
  111. {
  112. root=DeleteFromPos(root,6,0);
  113. }
  114. Print(root);
  115.  
  116. for(int i=0;i<n;i++)
  117. {
  118. root=DeleteFromEnd(root,4);
  119. }
  120. Print(root);
  121. }
Success #stdin #stdout 0s 5268KB
stdin
3
5 6 4
stdout
4->6->5->