LinkedList排序没有重复

时间:2014-12-26 17:00:30

标签: c linked-list

我想对链表进行排序,我写了这段代码:

courseList *sortList(courseList *list) 
{

// 
if(list == NULL || list->nextCourse == NULL)
    return list; // the list is sorted.

//replace largest node with the first : 

//1- find largest node : 
courseList *curr, *largest,*largestPrev ,*prev;
curr = list;
largest = list;
prev = list;
largestPrev = list;
while(curr != NULL) {

        if( strcmp(curr->courseName,largest->courseName)<0)/*curr->num > largest->num*/ {
            largestPrev = prev;
            largest = curr;
        }
        prev = curr;
        curr = curr->nextCourse;
   }
//largest node is in largest. 

//2- switching firt node and largest node : 
courseList *tmp;
if(largest != list)
{
    largestPrev->nextCourse = list;
    tmp = list->nextCourse;
    list->nextCourse = largest->nextCourse;
    largest->nextCourse = tmp;
}

// now largest is the first node of the list.

// calling the function again with the sub list :
//            list minus its first node :
largest->nextCourse = sortList(largest->nextCourse);


return largest;
}

例如,我的链接列表是这样的:

MATH101 CSE100 MATH259 BLAW203 MATH101 STAT253 STAT253 MATH259 MATH259 HIST111 STAT253

这就是我得到的:

BLAW203 CSE100 HIST111 MATH101 MATH101 MATH259 MATH259 MATH259 STAT253 STAT253 STAT253

但我想弄清楚如何摆脱这种重复

1 个答案:

答案 0 :(得分:1)

这将帮助您删除重复的字符串:

courseList *sortList(courseList *list)
{
    //
    if(list == NULL || list->nextCourse == NULL)
        return list; // the list is sorted.

    //replace largest node with the first :

    //1- find largest node :
    courseList *curr, *largest,*largestPrev ,*prev;
    curr = list;
    largest = list;
    prev = list;
    largestPrev = list;
    while(curr != NULL)
    {
            if( strcmp(curr->courseName,largest->courseName)<0)/*curr->num > largest->num*/ {
                largestPrev = prev;
                largest = curr;
            }
            prev = curr;
            curr = curr->nextCourse;
    }
    //largest node is in largest.

    //2- switching first node and largest node :
    courseList *tmp;
    if(largest != list)
    {
        largestPrev->nextCourse = list;
        tmp = list->nextCourse;
        list->nextCourse = largest->nextCourse;
        largest->nextCourse = tmp;
    }

    // now largest is the first node of the list.

    // calling the function again with the sub list :
    //            list minus its first node :


    // *****Changed*******

    courseList *next_node = sortList(largest->nextCourse);

    // Removing Repetition
    while(next_node != NULL)
    {
        if( strcmp(next_node->courseName,largest->courseName)==0)
          next_node = next_node->nextCourse;
        else
          break;
    }
    largest->nextCourse = next_node;

    // *****Changed*******

    return largest;
}