迭代方法 Iterative Method
Node * reverse( Node * ptr )
{
Node * next;
Node * previous = NULL;
while(ptr != NULL) {
next = ptr->next;
ptr->next = previous;
previous = ptr;
ptr = next;
}
return previous;
}
递归方法 Recursive Method
Node* reverse(Node *ptr)
{
if(ptr->next == NULL)
return ptr; //最右结点会一直传回到最外层
Node *q = p->next;
Node *head = reverse(q);
q->next = ptr; //反向接回
ptr->next = NULL;
return head;
}

本文详细介绍了使用递归和迭代方法在链表中实现元素反转的过程,包括具体代码实现和工作原理解析。
1251

被折叠的 条评论
为什么被折叠?



