Linked lists - insert function not sorting right
Sep 28, 2014 at 6:56am UTC
i made a linked list for video objects. i made an insert function to sort each video by title alphabet order.
when i run the code and chose insert all my videos, i type print and it works for a b c d e but it sorts wrong for f,u, i, p (typed exactly same order) it still prints out f, u, p, i the same order.
not sure why this is happening.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
main.cpp
31 while (getline(cin, command))
32 {
33
34 if (command=="insert" )
35 {
36
37 getline(cin, title);
38 getline(cin, url);
39 getline(cin, comment);
40 cin >> length;
41 cin >> rating;
42 cin.ignore();
43
44 myVideo = new Video(title, url, comment, length,rating);
45
46 list.insert(myVideo);
47 // list.print();
48 counter++;
49
50 /* if(m_head->m_video->get_title() == video->get_title())
51 {
52
53 cerr << "Title is already in the list" << endl;
54 }*/
55 }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
videolist.cpp
27 bool Vlist::insert(Video *video)
28 {
29 if (m_head==NULL)
30 {
31 m_head=new Node(video, NULL);
32 return true ;
33 }
34
35 /* if( m_head->m_next->m_video->get_title() >= video->get_title() )
36 {
37 */
38
39 if (m_head->m_video->get_title() >= video->get_title())
40 {
41 if (m_head->m_video->get_title() == video->get_title())
42 {
43
44 return false ;
45 }
46
47 m_head=new Node(video, m_head);
48 return true ;
49 }
50
51 Node *ptr=m_head;
52 while ( (ptr->m_next!=NULL) && ( video->get_title()>=ptr->m_video->get_title() ) )
53 //checking if first title is bigger than last
54 {
55 if (( video->get_title() == ptr->m_video->get_title() ) )
56 {
57 //error if same title
58 return false ;
59 }
60 ptr=ptr->m_next;
61 }
62 ptr->m_next=new Node(video, ptr->m_next);
63
64 return true ;
65 }
Last edited on Sep 28, 2014 at 6:59am UTC
Sep 29, 2014 at 4:13pm UTC
We can't make sense of what you've posted without seeing the definitions of the variables you're using.
Sep 30, 2014 at 1:44pm UTC
The code looks basically correct. What does Video::get_title() return? Also do you want to do a case-sensitive comparison?
Topic archived. No new replies allowed.