fork download
  1. #include <iostream>
  2. using namespace std;
  3. struct node{
  4. int data;
  5. struct node* next;
  6. };
  7. struct node* createnode(int val)
  8. {
  9. struct node* p=(struct node*)malloc(sizeof(struct node));
  10. p->data=val;
  11. p->next=NULL;
  12. return p;
  13. }
  14. struct node* insertsorted(struct node* head,int val)
  15. {
  16. struct node* temp1=NULL;
  17. struct node* temp=head;
  18. if(val<head->data)
  19. {
  20. temp1=createnode(val);
  21. temp1->next=head;
  22. head=temp1;
  23. return head;
  24. }
  25. while(temp->next!=NULL && temp->next->data<val)
  26. {
  27. temp=temp->next;
  28. }
  29. temp1=createnode(val);
  30. temp1->next=temp->next;
  31. temp->next=temp1;
  32. return head;
  33. }
  34. struct node* deletesorted(struct node* head,int pos)
  35. {
  36. struct node* temp=head;
  37. struct node* temp1=NULL;
  38. if(pos==1)
  39. {
  40. head=head->next;
  41. free(temp);
  42. return head;
  43. }
  44. while(pos>2 && temp->next!=NULL)
  45. {
  46. temp=temp->next;
  47. pos--;
  48. }
  49. temp1=temp->next;
  50. temp->next=temp->next->next;
  51. free(temp1);
  52. return head;
  53. }
  54. void printlinked(struct node* head)
  55. {
  56. while(head!=NULL)
  57. {
  58. cout<<head->data<<" ";
  59. head=head->next;
  60. }
  61. }
  62. int main() {
  63. struct node* head=createnode(1);
  64. head->next=createnode(3);
  65. head->next->next=createnode(5);
  66. head->next->next->next=createnode(6);
  67. struct node* result=insertsorted(head,1);
  68. printlinked(result);
  69. cout<<"\n";
  70. struct node* result1=deletesorted(head,5);
  71. printlinked(result1);
  72. return 0;
  73. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
1 1 3 5 6 
1 1 3 5