我被要求编写一个函数reverseHalves()来重新排列给定的链表,以便将节点的前半部分移到后半部分的后面。例如
给定链接列表[1 2 3 4 5 6]
,结果列表应为[4 5 6 1 2 3]
。
当给定的具有奇数个节点的链接列表,该列表应当是分裂与具有附加的节点中的第一半。也就是说,给定列表[1 2 3 4 5]
,结果列表应为[4 5 1 2 3]
。
但是我的函数将给出无限的输出...
typedef struct _listnode{
int item;
struct _listnode *next;
} ListNode;
typedef struct _linkedlist{
int size;
ListNode *head;
ListNode *tail;
} LinkedList;
这是我使用的功能:
// printList will print out the value in every nodes until there is a NULL
void printList(LinkedList *ll);
ListNode * findNode(LinkedList *ll, int index);
int insertNode(LinkedList *ll, int index, int value);
void reverseHalves(LinkedList *ll)
{
int index;
ListNode *new_head, *new_tail;
new_head = NULL;
new_tail = NULL;
// determine the index of new tail, and the new head which is index+1*
index = (ll->size + 1) / 2;
// get the new head by findNode func,whose index is index+1
// make new_head point to the node found*
new_head = findNode(ll, index);
// make initial tail->next be the initial head*
ll->tail->next = ll->head;
// set the head to be the new head
ll->head = new_head;
insertNode(ll, ll->size, -1);
new_tail = findNode(ll, ll->size);
new_tail = NULL;
}
最佳答案
这是一个大致要点:
new_head_index = (ll->size+1) / 2;
new_tail_index = new_head_index - 1;
if (new_tail_index < 0)
return;
new_head = findNode(ll,new_head_index);
new_tail = findNode(ll,new_tail_index);
ll->tail->next = ll->head;
new_tail->next = NULL
ll->head = new_head;
关于c - 倒排一半,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15984552/