链表反转操作

链表反转

#include 

typedef struct LNode{
    int data;
    struct LNode *next;
}LNode, *LinkList;

LinkList invert(LNode *h)
{
    LNode *s, *p;
    p=h->next;
    h->next = NULL;
    while(p!=NULL)
    {
        s=p;
        p=p->next;
        s->next=h;
        h=s;
    }
    return h;
}
void print_link(LNode *h)
{
    while(h!=NULL)
    {
        printf("%d ", h->data);
        h=h->next;
    }
    printf("\n");
}

int main()
{
    struct LNode num1={1, NULL};
    struct LNode num2={2, &num1};
    struct LNode num3={3, &num2};
    struct LNode num4={4, &num3};
    struct LNode num5={5, &num4};
    struct LNode num6={6, &num5};
    struct LNode num7={7, &num6};
    struct LNode *head = &num7;
    printf("反转前:\n");
    print_link(head);
    printf("反转后:\n");
    head = invert(head);
    print_link(head);
}

请添加图片描述

你可能感兴趣的:(c,链表,数据结构)