2015-09-27 76 views
1

我在通過鏈接列表進行搜索時遇到問題。我正在編寫一個成績簿程序,並且正在進行輸入錯誤檢查,以查看用戶是否進入了現有課程,以便讓學生參加該課程。需要幫助檢查C中的鏈接列表

所以這是一個雙向鏈表的課程信息的結構。

typedef struct Course_Info // Course information 
{ 
    int Course_ID; 
    char Course_Name[15]; 
    struct Course_Info *next; 
} Course; 

typedef struct // Linked list for Course 
{ 
    int Ctracker; // Keeps track of courses 
    Course *Course_Head; 
    Course *Course_Tail; 
} List_Course; 

和它們相應的變量以及初始化。

List_Student Students; 
List_Course Courses; 
Grade_List Grades; 

Students.Stracker = 0; 
Students.Student_Head = Students.Student_Tail = NULL; 

Courses.Ctracker = 0; 
Courses.Course_Head = Courses.Course_Tail = NULL; 

Grades.Grade_cnt = 0; 
Grades.Grade_Head = Grades.Grade_Tail = NULL; 

在這個函數中,我將招收一個學生到一門課程,但首先我要做一些輸入檢查,以確保課程存在。

void EnrollStudent(List_Course *Courses, List_Student *Students) 
{ 
    int CID; int SID; 

    printf("Enter course ID: "); 
    scanf("%d%*c", &CID); 

    if(CID != Courses -> Course_Head -> Course_ID) 
    { 
     printf("Course does not exist!\n"); 
     return; 
    } 
    else 
    { 
     printf("Found class!\n"); 
    } 
} 

我現在的問題是它只搜索鏈表的第一個元素。我該如何做一個檢查整個鏈表的循環?

回答

0
ListCourse * current = Courses->Course_Head; 
while ((NULL != current) && (CID != current->Course_ID)) current = current->next; 

if (NULL == current) printf("Course %d not found\n", CID); 
else printf("Course %d found\n", CID); 

你的問題是你沒有遍歷列表,而只是檢查列表頭。你需要維護一個指向你正在檢查的節點的指針並且迭代它(指向下一個節點),以防你找不到你想要的東西。如果沒有任何東西可以搜索,或者您找到了您要查找的內容,則可以退出。

1

迭代鏈表非常簡單。

你需要使用一個局部變量是列表的當前元素,你要初始化課程 - > Course_Head,如:

Course* current = Courses->Course_Head; 

然後直到current != NULL只需保持更新當前指向下一個元素,如:

while (current != NULL) { 
    // do what your want with current 
    current = current->next; 
} 

記住,在你的榜樣,你談論一個雙向鏈表但它是一個單鏈表有兩個指針頭和尾,雙鏈表有兩個指針中的每個節點兩個方向,讓你可以tr厭惡它倒序,這是你的情況並非如此。

+0

對不起!所以如果我正確地理解它,一個雙鏈表就是這樣的。 struct Course_Info ** next? – Cheezdue

+0

是或簡單地Course_Info * next,* prev; – Jack