#include<iostream>
using namespace std;
typedef struct node
{
int data;
node* next;
};
class List
{
private:
node* head;
node* last;
public:
List()//initialize linked list(初始化链表)
{
head = new node;
head->next = NULL;
last = head;
}
void CreateList(int a[], int length)
{
for (int i = 0; i < length; ++i)
{
node* temp = new node;
temp->data = a[i];
last->next = temp;
last = temp;
}
last->next = NULL;
}
void DisplayList()
{
if (head->next == NULL)
return;
for (node* p = head->next; p; p = p->next)
cout << p->data << '\t';
cout << endl;
}
void Swap()
{
if (head->next == NULL || head->next->next == NULL)
return;
//set the two pointer p and q to point to the front and the back node of the data field respectively,and then make the next node of the head node point to null
//设置p,q两个指针分别指向数据域的前后两个结点,再令头结点的下一个结点指向空
node* p = head->next;
node* q;
head->next = NULL;
node *last = head;
while (p)
{
q = p->next;
//when it is odd,the last node is directly connected
//当为奇数时,直接连接最后一个结点
if (q == NULL)
{
last->next = p;
last = p;
last->next = NULL;
return;
}
last->next = q;
last = q;
//at this time ,the first node address of the node to be exchanged must be recorded,otherwise the address will be lost
//此时一定要记录下一个要交换结点的首结地址不然地址丢失
node* temp;
temp=q->next;
last->next = p;
last = p;
last->next = NULL;
p = temp;
}
}
};
int main()
{
int a[6] = { 1,2,3,4,5,6};
List list;
list.CreateList(a, 6);
cout << "链表未交换结点前结果" << endl;
list.DisplayList();
cout << "链表交换结点后结果" << endl;
list.Swap();
list.DisplayList();
}
?
?
|