Q1:单链表的翻转

步骤

  • 由头插法建立单链表(实际上已经实现了一次逆转)
  • 构造函数,返回翻转后的单链表的头结点
  • 以头结点为开始结点输出单链表

可执行代码

#include <stdio.h>
#include <stdlib.h>

struct Node {
    
    
    int data;
    Node *next;
};

Node* reverseList(Node* head) 
{
    
    
    Node *prev = NULL;
    Node *curr = head;
    while (curr != NULL) //因为一直以来先开始变换的是curr = curr->next;
	{
    
    
		head=curr;
        curr = curr->next;
        head->next=prev;
        prev = head;
    }
    return head;
}

void printList(Node* head) 
{
    
    
	//并不会更改head的指向 
    while (head != NULL) 
	{
    
    
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}

int main() {
    
    
    Node *head = NULL;//新建一个单链表的头结点
    Node *temp = NULL;
    
	//头插法12345建立链表 
    for (int i = 1; i <= 5; i++) 
	{
    
    
        temp = (Node*)malloc(sizeof(Node));
        temp->data = i;
        temp->next = head;
        head = temp;
    }

    printf("Original List: ");
    printList(head);
    
    head = reverseList(head);

    printf("Reversed List: ");
    printList(head);

    return 0;
}

执行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45880844/article/details/129857457
Q1
今日推荐