首页 > 试题广场 >

反转单向链表

[编程题]反转单向链表
  • 热度指数:2852 时间限制:C/C++ 4秒,其他语言8秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
实现反转单向链表和双向链表的函数。
如 1->2->3 反转后变成 3->2->1。

输入描述:
第一行一个整数 n,表示单链表的长度。

第二行 n 个整数 val 表示单链表的各个节点。

第三行一个整数 m,表示双链表的长度。

第四行 m 个整数 val 表示双链表的各个节点。


输出描述:
在给定的函数内返回相应链表的头指针。
示例1

输入

3
1 2 3
4
1 2 3 4

输出

3 2 1
4 3 2 1

备注:


/* 仅实现单链表反转 */
#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int val;
    struct node *next;
} Node;

Node *newNode(int val);

void freeList(Node *head);

void printList(Node *head);

Node *createList(int n);

Node *reverseList(Node *head);

int main(void) {
    int n;
    Node *head = NULL;
    scanf("%d", &n);
    head = createList(n);
    head = reverseList(head);
    printList(head);
    freeList(head);
    scanf("%d", &n);
    head = createList(n);
    head = reverseList(head);
    printList(head);
    freeList(head);
    return 0;
}

Node *newNode(int val) {
    Node *node = (Node *) malloc(sizeof(Node));
    node->val = val;
    node->next = NULL;
    return node;
}

void freeList(Node *head) {
    Node *old;
    while (head != NULL) {
        old = head;
        head = head->next;
        free(old);
    }
}

void printList(Node *head) {
    Node *cur = head;
    while (cur != NULL) {
        printf("%d", cur->val);
        cur = cur->next;
        if (cur != NULL)
            printf(" ");
    }
    printf("\n");
}

Node *createList(int n) {
    Node *head = NULL, *cur = NULL, *node;
    int val;
    for (int i = 0; i < n; i++) {
        scanf("%d", &val);
        node = newNode(val);
        if (head == NULL) {
            head = node;
            cur = node;
            continue;
        }
        cur->next = node;
        cur = cur->next;
    }
    return head;
}

Node *reverseList(Node *head) {
    Node *next, *pre = NULL;
    while (head != NULL) {
        next = head->next;
        head->next = pre;
        pre = head;
        head = next;
    }
    return pre;
}

发表于 2022-02-06 23:18:54 回复(0)

问题信息

上传者:小小
难度:
1条回答 3659浏览

热门推荐

通过挑战的用户

查看代码