Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. //Matias Salohonka 0438604
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. typedef struct node *listpointer;
  6. typedef struct node{
  7. int value;
  8. listpointer next;
  9. } Node;
  10.  
  11. listpointer addNode(listpointer list, int i) {
  12. listpointer temp = NULL;
  13. temp = (listpointer)malloc(sizeof(Node)); //luodaan alkio
  14. temp->value = i;
  15. temp->next = NULL;
  16.  
  17. if(list == NULL) { //tyhjä lista
  18. list = temp;
  19. } else {
  20. listpointer ptr = list; //apuosoitin
  21. while(ptr->next != NULL) ptr = ptr->next; //listan loppuun
  22. ptr->next = temp; //alkio sinne
  23. }
  24. return list;
  25. }
  26.  
  27. listpointer removeNode(listpointer list, int i) {
  28. listpointer finder = list;
  29. listpointer temp;
  30.  
  31. while(finder->next->value != i) { //etsitään poistettavan alkion edellinen
  32. finder = finder->next;
  33. }
  34. temp = finder->next->next; //poistettavasta seuraava tilapäismuuttujaan
  35. free(finder->next); //vapautetaan poistettava
  36. finder->next = temp; //viittaus poistettavan edellisestä poistettavan seuraavaan
  37.  
  38. return list;
  39. }
  40.  
  41. void printList(listpointer list) {
  42. listpointer temp = list;
  43.  
  44. while(temp != NULL) {
  45. printf("%d\n",temp->value);
  46. temp = temp->next;
  47. }
  48. }
  49.  
  50. int main() {
  51.  
  52. listpointer list = NULL;
  53.  
  54. list = addNode(list, 2);
  55. list = addNode(list, 4);
  56. list = addNode(list, 6);
  57. list = addNode(list, 3);
  58. list = addNode(list, 7);
  59. list = addNode(list, 1);
  60. list = addNode(list, 9);
  61.  
  62. printList(list);
  63. printf("Nyt listalta poistetaan 6\n");
  64.  
  65. list = removeNode(list, 6);
  66.  
  67. printList(list);
  68.  
  69. return 0;
  70. }
  71.  
  72. //eof
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement