p62 练习3.3 通过只调整指针(而不是数据)来交换两个相邻的元素,使用:

由于两种数据结构的结点结构体都较为简单,这里就不列出了

a.单链表

List creatList1(List T,int n) //创建单链表 (头插法)
{
int x;Position S;
T = new struct Node;
T->Next = NULL;
for(int i = 0;i < n;i++)
{
S = new struct Node;
cin>>x;
S->Data = x;
S->Next = T->Next;
T->Next = S;
}
return T;
}


交换相邻结点算法:

void SwapAdjNode1(List T,Position P1,Position P2)
{
if(P1->Next!=P2)
{
cout<<"不是相邻结点";
return;
}
else
{
PtrToNode P0;
P0 = FindPrevious(P1->Data,T);
P1 = P2->Next;
P2->Next = P1;
P0->Next = P2;
return;
}
}


b:双链表

List creatList2(List T,int n) //创建双向链表
{
Position rear = T; //尾插法需要定义一个尾指针
Position S;
T = new struct Node;
T->Next= NULL;
T->prior = NULL;
for(int i = 0;i < n;i++)
{
S = new struct Node; //尾插法
cin>>S->Data;
rear->Next = S;
head->prior = S;
S->prior = rear;
S->Next = head;
rear = S;
}
return T;
}


交换相邻结点算法:

void SwapAdjNode2(List T,Position p1,Position p2)
{
 Position P0 = FindPrevious(p1->Data,List T); 
 Position P3 = p2->Next;
 if(P1->Next!=P2)
 {
  cout<<"不是相邻结点";
  return;
 }
 else
 {
  P0->Next = p2;
  p1->Next = p3;
  p1->prior = p2;
  p2->Next = p1;
  p2->prior = p0;
  p3->prior = p1;
 }
}


这里列出FindPreviou算法实现:

Position FindPrevious(DataType x,List T)  //寻找前置结点;
{
 PtrToNode p;
 p = T;
 while(p->Next!=NULL&&p->Next->Data!=x)
 {
  p = p->Next;
 }
 if(p->Next == NULL)
 {
  return NULL;
 }
 else return p;
}




转载于:https://www.cnblogs.com/Western-Trail/p/10326192.html

你可能感兴趣的:(数据结构与算法)