单链表的实现:
实际上将position->Next执行position->Next->Next之后,空出来的指针position->Next的操作类似于在节点之前插入一个指针元素。
基于之前已经创建好的单链表。
static void swip(Position position_ahead, Position position)
{
Position position_next = position->Next;
position->Next = position->Next->Next;
position_next->Next = position;
position_ahead->Next = position_next;
}
运行结果:
element is 0
element is 1
element is 2
element is 3
element is 4
element is 6
调整之后element is 0
element is 2
element is 1
element is 3
element is 4
element is 6
添加创建双链表的方法:实际上创建双链表的方法十分的简单,就是在单链表的基础上加上一个Ahead
头文件中申明
typedef struct Node *PtrToNode;
typedef PtrToNode Position;
typedef PtrToNode List;
typedef int NodeElement;
struct Node {
Position Ahead;
NodeElement element;
Position Next;
};
static Position CreateListCell(List ahead, NodeElement element);
static List CreateHead();
static void OverViewList(List head);
.c文件中编写具体的实现
#include<stdio.h>
#include<string.h>
#include<sys/time.h>
#include<stdlib.h>
#include<errno.h>
#include"double_list.h"
static Position CreateListCell(List ahead, NodeElement element){
Position position = NULL;
position = (Position)malloc(sizeof(struct Node));
if(position==NULL){
fprintf(stderr, "there is no space\n");
return NULL;
}
position->element = element;
ahead->Next = position;
position->Ahead = ahead;
position->Next = NULL;
return position;
}
static List CreateHead()
{
List head = NULL;
Position position = NULL;
head = (Position)malloc(sizeof(struct Node));
if(head==NULL){
fprintf(stderr, "there is no space\n");
return NULL;
}
head->element = 0;
head->Next = NULL;//此处未指明Ahead为NULL,在某些编译器中将出现断错误
return head;
}
static void OverViewList(List tail)
{
Position position = tail;
while(position!=NULL){
printf("element is %d\n", position->element);
position = position->Ahead;
}
}
static Position CreateList1()
{
List head = CreateHead();
Position position = NULL;
position = CreateListCell(head, 1);
position = CreateListCell(position, 2);
position = CreateListCell(position, 3);
position = CreateListCell(position, 4);
position = CreateListCell(position, 6);
return position;
}
int main()
{
List tail = CreateList1();
OverViewList(tail);
}
前后两个相邻元素的交换相对单链表要复杂一点。
例子如下:
static void swip(Position ahead, Position position)
{
Position position_next = position->Next;
position->Next = position_next->Next;
position_next->Next->Ahead = position;
ahead->Next = position_next;
position_next->Ahead = ahead;
position_next->Next = position;
position->Ahead = position_next;
}