列出单链表反转的4种方法,并且用C语言写出
时间: 2023-03-14 15:21:58 浏览: 99
单链表反转的4种方法包括:1. 遍历法:从第一个节点开始,把每个节点的指针指向它的前一个节点。C语言实现:
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* pre = NULL;
struct ListNode* cur = head;
struct ListNode* next;
while(cur != NULL) {
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}2. 递归法:从最后一个节点开始,把当前节点的指针指向它的前一个节点。C语言实现:
struct ListNode* reverseList(struct ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
struct ListNode* new_head = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return new_head;
} 3. 头插法:从第一个节点开始,把每个节点插入到新链表的头部。C语言实现:
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* new_head = NULL;
struct ListNode* cur = head;
while(cur != NULL) {
struct ListNode* next = cur->next;
cur->next = new_head;
new_head = cur;
cur = next;
}
return new_head;
}4. 就地反转法:从第一个节点开始,把当前节点的指针指向它的后一个节点。C语言实现:
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* pre = NULL;
struct ListNode* cur = head;
while(cur != NULL) {
struct ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
阅读全文