逆转单链表
1. 非递归实现
(1) (没有头节点的)其中 List 跟 Position 是结构指针;
typedef struct Node {
int value;
struct Node *next;
} *List;
typedef List Position;
List
ReverseList( List L ) { // Assuming no header.
if( L == NULL )
return L;
Position PreviousPos, CurrentPos, NextPos;
PreviousPos = NULL;
CurrentPos = L;
NextPos = L->next;
while( NextPos != NULL ) {
CurrentPos->next = PreviousPos;
PreviousPos = CurrentPos;
CurrentPos = NextPos;
NextPos = NextPos->next;
}
CurrentPos->next = PreviousPos;
return CurrentPos;
}
(2) (有头结点的)
typedef struct Node {
int value;
struct Node *next;
} *List;
typedef List Position;
List
ReverseList( List L ) { // Assumed header
if( L == NULL )
return L;
if( L->next == NULL )
return L;
Position PreviousPos, CurrentPos, NextPos;
PreviousPos = NULL;
CurrentPos = L->next;
NextPos = CurrentPos->next;
while( NextPos != NULL ) {
CurrentPos->next = PreviousPos;
PreviousPos = CurrentPos;
CurrentPos = NextPos;
NextPos = NextPos->next;
}
CurrentPos->next = NextPos;
L->next = CurrentPos;
return L;
}
2. 递归实现
p1 和 p2 指针分别指向当前递归子链表 list1 的第一个和第二个结点。然后对以 p2 为首结点的子链表 list2 进行递归逆转;则 p2 节点将成为 list2r 逆转后的尾结点,而此时函数返回的头结点将是原 list2 的尾结点(如下图)。最后我们只要把 p2 的 next 指向 p1 就可以了。
(1) 递归实现
typedef struct Node {
int value;
struct Node *next;
} *List;
typedef List Position;
List
ReverseList( List L ) { // Assuming no header
if( L == NULL )
return L;
if( L->next == NULL )
return L;
Position p1, p2;
p1 = L;
p2 = p1->next;
L = ReverseList( p2 );
p2->next = p1;
p1->next = NULL;
return L;
}