struct LNode{
int e;
LNode* next;
};
typedef struct LNode* LinkList;
int e;
LNode* next;
};
typedef struct LNode* LinkList;
非遞歸方法:
//l 是帶頭結點的單鏈表
void ReverseList(LinkList l){
if(l==NULL || l->next == NULL)
return;
LNode *p, *q, *r;
p = l->next;
q = p->next;
while( q != NULL){
r = q->next;
q->next = p;
p = q;
q = r;
}
l->next->next = NULL;
l->next = p;
}
void ReverseList(LinkList l){
if(l==NULL || l->next == NULL)
return;
LNode *p, *q, *r;
p = l->next;
q = p->next;
while( q != NULL){
r = q->next;
q->next = p;
p = q;
q = r;
}
l->next->next = NULL;
l->next = p;
}
遞歸方法:
LNode* ReverseList_Recursive(LNode* pNode,LinkList& l){
if ( (pNode == NULL) || (pNode->next == NULL) ){
l->next->next = NULL;
l->next = pNode;
return pNode;
}
LNode* temp = ReverseList_Recursive(pNode->next, l);
temp->next = pNode;
return pNode;
}
if ( (pNode == NULL) || (pNode->next == NULL) ){
l->next->next = NULL;
l->next = pNode;
return pNode;
}
LNode* temp = ReverseList_Recursive(pNode->next, l);
temp->next = pNode;
return pNode;
}