Infinite Loop Linked List C -
i working on practice problem improve c. here question:
write function sort linked list of integers follows:
a) find largest value in list.
b) delete position , insert @ head of list.
c) starting second element, repeat (a) , (b).
d) starting third element, repeat (a) , (b).
continue until list sorted.
my sorting function:
nodeptr sortlist(nodeptr np) { nodeptr makenode(int), head, temp; head = temp = np; if (np != null) { // determine linked list length int len = 0; while (temp != null) { len++; temp = temp -> next; } int i; (i = 0; < len; i++) { temp = head; int j; // traverse spot j in linked list (j = 0; j < i; j++) { temp = temp -> next; } // find largest nodeptr largest, prev, prevtolargest; largest = prev = prevtolargest = temp; while (temp != null) { if (temp -> num > largest -> num) { largest = temp; prevtolargest = prev; } if (temp != prev) prev = prev -> next; temp = temp -> next; } prevtolargest -> next = largest -> next; largest -> next = head; head = largest; } } return head; }
using debugger have discovered list sorted infinite. believe have created circular linked list, i'm not sure how fix that.
thanks help!
a couple of things. first when asking people debug code try include line numbers makes easier reference issues. ok actual issues.
if (temp != prev) prev = prev -> next;
on line of code have prev = temp, rather prev -> next since temp next one, it's not big of issue think makes easier follow along.ok insert largest before head making
largest->next = head
. index before spot inserted still pointing head rather largest, have broken link in linked list. *** talking code afterprevtolargest -> next = largest -> next;
near end.when return head, head been moved multiple times. code time iterate through entire list head moved last element in list, since have
head = largest;
, last largest element going smallest element @ end of list. before returning head try pointing first element in list.
see if might fix issue. there might more bugs these ones stood out me.
Comments
Post a Comment