【链表】通过只调整指针(不是数据)来交换两个相邻的元素:单链表和双链表实现

单链表的实现:

实际上将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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值