单链表的逆转实现

typedef int datatype;
struct node
{
       datatype data;
       node *next;
};

node * reverse(node *&head)
{
     if (head->next == NULL || head == NULL)
     return NULL;
     else
     {
         node *P = head->next;
         node *Q = P->next;
         while (Q->next)
         {
               node *S = Q->next;
               Q->next = P;
               P = Q;
               Q = S;
               //P = P->next; 
         }
         Q->next = P;
         head->next->next = NULL;
         head->next = Q;

         return head;
     }
}

时隔4年更新如下:

node* reverse(node* head)
{
    if(!head || !head->next)
        return head;
    node* P = head->next;
    node* Q = P->next;
    while(Q)
    {   
        node* S = Q->next;
        Q->next = P;
        P = Q;
        Q = S;
    }   
    head->next->next = head;
    head->next = NULL;
    return P;
}

你可能感兴趣的:(数据结构与算法,面试笔试总结)