fork download
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. struct Student {
  5. int id;
  6. char* name;
  7. Student* next;
  8. Student* prev;
  9. };
  10.  
  11. Student* createStudent(const int id, const char* name, Student* pNext, Student* pPrev) {
  12. struct Student* pStudent = new Student;
  13. pStudent->id = id;
  14. pStudent->name = new char[strlen(name)];
  15. strcpy(pStudent->name, name);
  16. pStudent->next = pNext;
  17. pStudent->prev = pPrev;
  18. return pStudent;
  19. }
  20.  
  21. Student* getLast(Student* pCurrent) {
  22. while(pCurrent->next != NULL) {
  23. pCurrent = pCurrent->next;
  24. }
  25. return pCurrent;
  26. }
  27.  
  28. void insertFirst(Student*& pHead, const int id, const char* name) {
  29. if(pHead == NULL) {
  30. pHead = createStudent(id, name, NULL, NULL);
  31. } else {
  32. pHead = createStudent(id, name, pHead, NULL);
  33. pHead->next->prev = pHead;
  34. }
  35. }
  36.  
  37. void append(Student*& pHead, const int id, const char* name){
  38. if(pHead == NULL) {
  39. pHead = createStudent(id, name, NULL, NULL);
  40. } else {
  41. struct Student* pCurrent = pHead;
  42. while(pCurrent->next != NULL) {
  43. pCurrent = pCurrent->next;
  44. }
  45.  
  46. pCurrent->next = createStudent(id, name, NULL, pCurrent);
  47. }
  48. }
  49.  
  50. void printItem(Student* pItem) {
  51. if (pItem == NULL) {
  52. std::cout << "addr: NULL;" << std::endl;
  53. } else {
  54. std::cout << "addr:" << pItem << "; next:"
  55. << pItem->next << "; prev:"
  56. << pItem->prev << "; id:"
  57. << pItem->id << "; name:"
  58. << pItem->name << ";" << std::endl;
  59. }
  60. }
  61.  
  62. int main() {
  63. Student* pHead = NULL;
  64. append(pHead, 10, "Hello0");
  65. append(pHead, 11, "Hello1");
  66. append(pHead, 11, "Hello2");
  67. insertFirst(pHead, 10, "Hello-1");
  68.  
  69. Student* pCurrent = pHead;
  70. while (pCurrent != NULL) {
  71. printItem(pCurrent);
  72. pCurrent = pCurrent->next;
  73. }
  74. std::cout << std::endl;
  75. return 0;
  76. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
addr:0x2ac11f4b8d10; next:0x2ac11f4b8c20; prev:0; id:10; name:Hello-1;
addr:0x2ac11f4b8c20; next:0x2ac11f4b8c70; prev:0x2ac11f4b8d10; id:10; name:Hello0;
addr:0x2ac11f4b8c70; next:0x2ac11f4b8cc0; prev:0x2ac11f4b8c20; id:11; name:Hello1;
addr:0x2ac11f4b8cc0; next:0; prev:0x2ac11f4b8c70; id:11; name:Hello2;