Инвертировать линейный список - C (СИ)
Формулировка задачи:
Инвертировать список, т.е. в заданном списке переставить элементы, чтобы они следовали в порядке, обратном исходному.
Решение задачи: «Инвертировать линейный список»
textual
Листинг программы
#include <stdio.h>
#include <stdlib.h>
struct node
{
int item;
node *next;
};
struct list
{
node *head;
node *tail;
};
void initlist(list& lst)
{
lst.head = NULL;
lst.tail = NULL;
}
void addtolist(list& lst, int item)
{
if(lst.tail == NULL)
lst.tail = new node;
else
{
lst.tail->next = new node;
lst.tail = lst.tail->next;
}
lst.tail->item = item;
lst.tail->next = NULL;
if(lst.head == NULL)
lst.head = lst.tail;
}
void printlist(list& lst)
{
node* p = lst.head;
while(p != NULL)
{
printf("%d ", p->item);
p = p->next;
}
printf("\n");
}
void reverse(list& lst)
{
node* p = lst.head->next;
lst.head->next = NULL;
node* prev = lst.head, *p2;
while(p != NULL)
{
p2 = p->next;
p->next = prev;
prev = p;
p = p2;
}
lst.tail = lst.head;
lst.head = prev;
}
int main(int argc, char *argv[])
{
list ls1;
initlist(ls1);
addtolist(ls1, 1);
addtolist(ls1, 3);
addtolist(ls1, 5);
addtolist(ls1, 2);
printlist(ls1);
reverse(ls1);
printlist(ls1);
system("PAUSE");
return 0;
}