当前位置:网站首页>C: Reverse linked list

C: Reverse linked list

2022-06-26 20:38:00 The wind is as calm as a cloud

Reverse linked lists are often used as interview questions , The answers I have read are not clear and easy to understand .

I think so : Reversing a linked list is actually taking the list out of the head in turn , Then add it to another linked list :

#include <stdio.h>

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

struct Node* popFromHead(struct Node **head)
{
	if(*head != 0 )
	{
		struct Node* first = *head;
		*head = first->next;
		return first;
	}
	else
	{
		return 0;
	}
}

void pushToHead(struct Node** head, struct Node* t)
{
	t->next = *head;
	*head = t;
}

void printList(struct Node *head)
{
	while(head != 0)
	{
		printf("%d ", head->data);
		head = head->next;
	}
	printf("\n");
}

int main()
{
	struct Node *head = 0;
	struct Node n1, n2, n3;
	n1.data = 1;
	n2.data = 2;
	n3.data = 3;
	pushToHead(&head, &n3);
	pushToHead(&head, &n2);
	pushToHead(&head, &n1);
	printList(head);

	struct Node* pNode = 0;
	struct Node* reverseList = 0;

	while((pNode = popFromHead(&head)) != 0)
	{
		pushToHead(&reverseList, pNode);
	}
	printList(reverseList);
    return 0;
}

 Run program output :
1 2 3 
3 2 1 
 It can be seen that the linked list has been reversed 

原网站

版权声明
本文为[The wind is as calm as a cloud]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206262022010333.html