单链表的逆置算法

单链表的逆置

学会了逆置单链表

单链表的逆置算法_第1张图片
结构体

#include 
#include 

typedef struct node
{
     
    int data;
    struct node *next;
}list,*plist;

建立链表代码

plist create(plist head)
{
     
    plist p,q;
    int n;
    head=(plist)malloc(sizeof(list));
    head->next=NULL;
    q=head;
    scanf("%d",&n);
    while(n!=-1)
    {
     
        p=(plist)malloc(sizeof(list));
        p->data=n;
        q->next=p;
        q=p;
        scanf("%d",&n);
    }
    q->next=NULL;
    return head;
}

链表的逆置代码‘
P指向链表第一个元素,断开头结点与链表,再头插法建立新链表,每下一个结点始终在第一个位置
代码如下

plist nizhi(plist head)//逆置算法
{
     
    plist p,q;
    p = head->next;    //P指向链表第一个元素
    head->next = NULL; //断开头结点与链表
    while(p != NULL)
    {
     
        q = p;
        p = p->next;
        q->next = head->next;  //相当于头插法构建新的链表
        head->next = q;//每下一个结点始终在第一个位置
    }
    return head;
}

此为主函数

int main()
{
     
    plist head,s;
    head=create(head);
    s=head->next;
    while(s)
    {
     
        printf("--%d",s->data);
        s=s->next;
    }
    printf("\n");
    head=nizhi(head);
    s=head->next;
    while(s)
    {
     
        printf("--%d",s->data);
        s=s->next;
    }
    return 0;
}

你可能感兴趣的:(单链表的逆置算法)