线性表的就地逆置(数组实现+链表实现)

头插法且头节点为空的链表的就地逆置方法

void Reverse_l(LinkList &L){
    LinkList p=L->next;
    L->next = NULL;
    while (p!=NULL) {
        LinkList r=p->next;
        p->next=L->next;
        L->next=p;
        p=r;
    }
}
#include 
#include 
#include 

using namespace std;

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

void insert1(int *a, LinkList &head, int elenum)
{
    LinkList p1 = head;
    LinkList p2;
    for (int i = 1; i <= elenum; i++) {
        scanf ("%d", &a[i]);
        p2 = (LinkList)malloc(sizeof(Node));
        p2->data = a[i];
        p1->next = p2;
        p1 = p2;
    }
    p2->next = NULL;
}

void transform1(int *a, int elenum)
{
    for (int i = 1; i <= elenum / 2; i++) {
        int t = a[i];
        a[i] = a[elenum - i + 1];
        a[elenum - i + 1] = t;
    }
}

void Reverse_l(LinkList &L){
    LinkList p=L->next;
    L->next = NULL;
    while (p!=NULL) {
        LinkList r=p->next;
        p->next=L->next;
        L->next=p;
        p=r;
    }
}

void print1(int *a, LinkList head, int elenum)
{
    for (int i = 1; i <= elenum; i++) {
        printf ("%d ", a[i]);
    }
    printf ("\n");
    LinkList p = head->next;
    while (p != NULL) {
        printf ("%d ", p->data);
        p = p->next;
    }
    printf ("\n");
}

void CreatList_head(LinkList &head, int elenum)
{
    head = (LinkList)malloc(sizeof(LinkList));
    head->next = NULL;
}

int main()
{
    int elenum;
    scanf ("%d", &elenum);
    int a[elenum + 1];
    LinkList head;
    CreatList_head (head, elenum);
    insert1 (a, head, elenum);
    transform1 (a, elenum);
    Reverse_l (head);
    print1 (a, head, elenum);
    return 0;
}

你可能感兴趣的:(acm水题)