单链表
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int val;
Node* next;
};
void Create(Node* head)
{
int n;
cin >> n;
Node *head1 = head;
for(int i = 0 ; i < n ; i++)
{
int x;
cin >> x;
if(i==0)
{
head1->val = x;
}
else
{
Node *temp = new Node();
temp->val = x;
head1->next = temp;
head1 = head1->next;
}
}
}
void show(Node *head)
{
while(head!=NULL)
{
cout << head->val << endl;
if(head->next != NULL) head = head->next;
else break;
}
}
int main()
{
Node* head = new Node();
Create(head);
show(head);
}
双向链表:
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int val;
Node* next;
Node* pre;
};
int n;
Node* Create(Node* head)
{
cin >> n;
Node *head1 = head;
for(int i = 0 ; i < n ; i++)
{
int x;
cin >> x;
if(i==0)
{
head1->val = x;
}
else
{
Node *temp = new Node();
temp->val = x;
temp->pre = head1;
head1->next = temp;
head1 = head1->next;
}
}
return head1;
}
void show(Node *last)
{
if(!n) return;
while(last!=NULL)
{
cout << last->val << endl;
if(last->pre != NULL) last = last->pre;
else break;
}
}
int main()
{
Node* head = new Node();
Node* last = new Node();
last = Create(head);
show(last);
}
单链表就地反转:
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int val;
Node* next;
};
int n;
Node * Create(Node* head)
{
cin >> n;
Node *head1 = head;
for(int i = 0 ; i < n ; i++)
{
int x;
cin >> x;
if(i==0)
{
head1->val = x;
}
else
{
Node *temp = new Node();
temp->val = x;
head1->next = temp;
head1 = head1->next;
}
}
return head;
}
void show(Node *head)
{
if(!n) return ;
while(head != NULL)
{
cout << head->val << endl;
head = head -> next;
}
}
Node* Reverse(Node *head)
{
Node *p = head; // 上一个点
Node *q = head->next; // 正在处理的点
Node *r = head;//下一个点
head->next = NULL;//反转后尾指针的next为空
while(q != NULL)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
return p;
}
int main()
{
Node* head = new Node();
Node* last = new Node();
last = Create(head);
show(Reverse(last));
}
双向循环链表:
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int val;
Node* next;
Node* pre;
};
int n;
Node* Create(Node* head)
{
cin >> n;
Node *head2 = head;
Node *head1 = head;
for(int i = 0 ; i < n ; i++)
{
int x;
cin >> x;
if(i==0)
{
head1->val = x;
}
else
{
Node *temp = new Node();
temp->val = x;
temp->pre = head1;
head1->next = temp;
head1 = head1->next;
if(i==n-1) // 首位相接
{
head2->pre = head1;
head1->next = head2;
}
}
}
return head1;
}
void show(Node *last)
{
if(!n) return;
while(last!=NULL)
{
cout << last->val << endl;
if(last->pre != NULL) last = last->pre;
else break;
}
}
int main()
{
Node* head = new Node();
Node* last = new Node();
last = Create(head);
show(last);
}