单链表的头插与逆置

逆置的思路:节点数在2个或2个以下就没有必要逆置
p指向list->head->next,先把list->head置为空,此时头节点就变成了最后一个节点,把p赋给s,p往后挪,挪一步赋给s(循环p!=NULL的条件下),s每次头插,也就是每次的倒数第二个变成了第二个节点,指向了一开始头节点置为空的节点,就实现了逆置

typedef int ElemType;
typedef struct Node
{
       ElemType data;
       Node *next;
}Node;
typedef struct List
{
       Node *head;
       ElemType currentsize;
}List;
Node *BuyNode()
{
       Node *p = (Node*)malloc(sizeof(Node));
       p->data = 0;
       p->next = NULL;
       return p;
}
void FreeNode(Node* p)
{
       free(p);
}
void Init_List(List *plist)
{
       if (plist == NULL)return;
       plist->head = BuyNode();
       plist->currentsize = 0;
}
void push_front(List *plist, ElemType x)
{
       Node *pGet = BuyNode();
       if (NULL == pGet)
       {
              return;
       }
       pGet->data = x;
    pGet->next = plist->head->next;
       plist->head->next = pGet;
       plist->currentsize++;
}
//void ResNode(List *plist)//逆置非递归
//{
//     Node *p = plist->head->next;
//     plist->head->next = NULL;
//     while (p != NULL)
//     {
//            Node*s = p;
//            p = p->next;
//            s->next = plist->head->next;
//            plist->head->next = s;
//     }
//}
void ResNode(List *plist, Node *p)//递归
{
       if (p != NULL)
       {
              Node *s = p;
              p = p->next;
              s->next = plist->head->next;
              plist->head->next = s;
              ResNode(plist, p);
       }
}
void Res_list(List *plist)
{
       if (plist == NULL || plist->currentsize <= 2)
       {
              return;
       }
       Node *p = plist->head->next;
       plist->head->next = NULL;
       ResNode(plist, p);
}
//void Print_List(Node *p)//打印的非递归
//{
//     while (p != NULL)
//     {
//            cout << p->data << " ";
//            p = p->next;
//     }
//}
void Print(Node *p)//打印的递归
{
       if (p != NULL)
       {
          Print( p->next);
          cout << p->data << " ";
          }

}
void Print_list(List *plist)
{
       if (plist == NULL)
       {
              return;
       }
       Print(plist->head->next);
       cout << endl;
}
int main()
{
       List plist;
       Init_List(&plist);
       push_front(&plist, 10);
       push_front(&plist, 20);
       push_front(&plist, 30);
       push_front(&plist, 40);
       Print_list(&plist);
       Res_list(&plist);
       Print_list(&plist);
}

猜你喜欢

转载自blog.csdn.net/wjh814/article/details/81023116