(No head node) where List and Position are structure pointers;
struct Node { int value; struct Node **list;typedef List Position;
listreverselist (List L) {//assuming no header. if(L = =NULL)returnL; 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; returnCurrentpos;}
(with a head node) cannot be used at the beginning of judgment (L = = NULL | | L->next = = null) or (L = = NULL && L->next = = null) inside the judging conditions must be written separately, as for why, carefully think should be clear.
listreverselist (List L) {//assumed header if(L = =NULL)returnL; if(L->next = =NULL)returnL; 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; returnL;}
(Here is a recursive implementation, this recursive implementation of the method is referred to from:
(Http://blog.163.com/[email protected]/blog/static/26599443201282083655446/)
However, his recursive implementation of the code is wrong.
The P1 and P2 pointers point to the first and second nodes of the current recursive sub-list List1, respectively. Then, a recursive reversal is made to the list2 of the P2-headed node, and the P2 nodes become the tail nodes after the LIST2R reversal, and the head node returned by the function is the tail node of the original List2 (for example). In the end we just have to point P2 's next to P1 to be OK.
Here's the corrected code.
listreverselist (List l) { // Assuming no header if(L = = NULL) return L; if (L->next = = NULL ) return L; Position P1, p2; = L; = P1->Next; = reverselist (p2); P2->next = P1; P1->next = NULL; return L;}
Reverse single-linked list