void R_Print(LinkList){
//从尾到头输出单链表L中每个结点的值
if(L->next!=NULL){
R_Print(L->next); //递归
} //if
if(L!=NULL)print(L->data); //输出函数
}
void R_Ignore_Head(LinkList L){
if(L!=NULL)
R_Print(L->next);
}
问题:
1.递归函数中,通过判定递归结束条件L->next==NULL已经到表尾了,为什么还要if(L!=NULL)来判断
程序里只是将链表尾的数据进行打印输出。
不知道你这个问题是否已经解决, 如果还没有解决的话:答案:
单链表的原地逆置操作,就是将链表头指针指向原链表的尾节点,尾节点指针指向原链表头节点,然后递归反转这个新链表。实现该操作的代码如下:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
这个递归函数的实现过程中,需要判断L!=NULL的条件,是因为我们在进行递归时需要传入头指针。如果头指针为NULL,则无法执行任何操作,因此需要先做这个判断。而在判定递归结束条件时,需要判断L->next==NULL,是因为在原地逆置操作中,需要找到原链表的尾节点,然后将尾节点指针指向原链表头节点,即newHead返回的节点。
示例代码:
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
void printList(ListNode* head) {
ListNode* cur = head;
while (cur != NULL) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
cout << "Original list: ";
printList(head);
head = reverseList(head);
cout << "Reversed list: ";
printList(head);
return 0;
}