我試圖創建一個功能splitlist(),將單鏈表分成兩個子列表 - 一個是前半部分,一個是後半。我想出了下面這將是第一次,我調用該函數的工作代碼,但是當我反覆調用函數,程序崩潰。有關如何更改我的代碼以防止出現此類錯誤的任何建議?函數splitlist()是無效的,因爲它打印兩個包含frontList和backList的列表。拆分鏈表到一半
typedef struct _listnode {
int item;
struct _listnode *next;
} ListNode;
typedef struct _linkedlist {
int size;
ListNode *head;
} LinkedList;
void splitlist(LinkedList* list1, LinkedList * firsthalf, LinkedList *secondhalf)
{
ListNode *cur = list1->head;
ListNode *front = firsthalf->head;
ListNode *back = secondhalf->head;
int totalnodes = list1->size;
int i;
if (totalnodes % 2 != 0) //if odd number of elements, add 1 to make it easier for traversal of list
{
totalnodes = totalnodes + 1;
}
int halfnodes = totalnodes/2;
{
for (i = 0; i < halfnodes; i++)
{
if (firsthalf->head == NULL) //initialise the head
{
firsthalf->head = malloc(sizeof(ListNode)); //create first node
front = firsthalf->head;
}
else
{
front->next = malloc(sizeof(ListNode));
front = front->next;
}
front->item = cur->item; // insert value from list1 into firsthalf
cur = cur->next; //point to next node in list1
}
front->next = NULL; //last node
for (i = halfnodes; i < totalnodes; i++)
{
if (secondhalf->head == NULL)
{
secondhalf->head = malloc(sizeof(ListNode));
back = secondhalf->head;
}
else
{
back->next = malloc(sizeof(ListNode));
back = back->next;
}
back->item = cur->item;
cur = cur->next;
}
back->next = NULL;
}
}
啊....有一些教授把這個作爲家庭作業。已經有一個答案。見http://stackoverflow.com/questions/33611261/split-linked-list/33611662#33611662 –
「但是當我反覆調用的函數,程序崩潰。」請澄清你這是用[MCVE(http://stackoverflow.com/help/mcve)表示函數是如何調用的意思。事實上,不清楚該函數的每個調用的輸入是什麼。 – kaylum
這並不真正拆分清單;它將半列表的副本創建爲兩個列表。 –