【发布时间】:2021-02-27 02:35:29
【问题描述】:
我们给了一个任务来反转一个单链表,但出于某种原因,我正在努力解决它 它应该反转,但是应该是尾巴的头部消失了,我不知道为什么,即使在调试之后
'''
void Reverse(struct node *head) {
struct node *last = NULL;
struct node *current = NULL;
struct node *temp = NULL;
current = head;
while (current->next != NULL) { //getting ptr to last item of the list
current = current->next;
last = current;
};
current = head; //resseting the current ptr back to the head of the list
while (current->next->next != NULL) { //getting the current ptr to one before the tail item
current = current->next;
};
temp = last;
while (last != head) {
if (current->next == last) {
last->next = current;
last = current;
current = head;
if (last == head) {
head->next = NULL;;
head->data = temp->data;
head->next = temp->next;
break;
};
};
};
};
'''
【问题讨论】:
-
任何反转列表的函数都需要改变头部,并以某种方式返回它。你什么都没做。
标签: c data-structures singly-linked-list