#include <iostream>
struct node
{
int data;
node* next;
node(int e_data, node* e_next)
{
data = e_data;
next = e_next;
}
};
node* create_ll(int a[], int n)
{
node* head = NULL;
node* cur = NULL;
for (int i = 0; i < n; ++i)
{
if (!head)
{
head = new node(a[i], NULL);
cur = head;
}
else
{
cur->next = new node(a[i], NULL);
cur = cur->next;
}
}
return head;
};
void swap(node* &head)
{
if (!head)
return;
node* next = head->next;
if (!next)
return;
else
{
swap(next->next);
head->next->next = next->next;
}
head->next = next->next;
next->next = head;
head = next;
};
int main(int argc,char *argv[])
{
int a[] = {0, 1, 2, 3, 4};
int len = sizeof(a) / sizeof(a[0]);
node* head = create_ll(a, len);
swap(head);
return 0;
}
Given a linked list, swap values inside nodes.
最新推荐文章于 2022-05-15 23:15:19 发布