C语言笔记31 •单链表经典算法OJ题-3.反转链表•

发布于:2024-07-11 ⋅ 阅读:(26) ⋅ 点赞:(0)

反转链表

1.问题

给你单链表的头节点 head,请你反转链表,并返回反转后的链表。

2.代码实现:

//3.反转链表
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>



typedef int SLTDataType;

typedef struct SListnode
{
	SLTDataType val;
	struct SListnode* next;
}ListNode;

ListNode* createNode(SLTDataType val)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc");
		exit(1);
	}
	newnode->val = val;
	newnode->next = NULL;
	return newnode;
}



struct ListNode* reverseList(struct ListNode* head)
{
	if (head == NULL)
	{
		return head;
	}
	ListNode* n1,*n2,*n3 ;
	n1= NULL, n2=head, n3=n2->next;//创建三个节点
	while (n2)
	{
		n2->next = n1;// 指针逆向
		n1 = n2;
		n2 = n3;
		if (n3)
		{
			n3 = n3->next;
		}
	}
	return n1;
}

int main()
{
	ListNode* node1, * node2, * node3, * node4, * node5;

	node1 = createNode(1);
	node2 = node1->next = createNode(2);
	node3 = node2->next = createNode(3);
	node4 = node3->next = createNode(4);
	node5 = node4->next = createNode(5);//创建一个链表

	ListNode* newhead = reverseList(node1);//反转链表

	while (newhead)
	{
		printf("%d ", newhead->val);
		newhead = newhead->next;
	}
	return 0;
}