您的位置:首页 > 其它

建立单链表并交换表中任意两个元素

2017-03-12 15:08 316 查看
/*
*功能:建立单链表并交换表中任意两个元素
*@time:2017年3月12日15:07:25
*/
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>

typedef struct node
{
int pos;
int data;
node* next;
}*LinkList,*linkNode;

LinkList CreateList_H();	//创建链表
void printList(LinkList L);	//打印链表
LinkList findPoint(const LinkList head,int pos);	//找到指定结点
LinkList findPre(const LinkList head,const LinkList node);//找到前结点
void swapPoint(linkNode head,linkNode node1,linkNode node2);//交换目标结点
int getLength(LinkList );			//获得链表长度
int posInput(int n);				//要找的结点位置
int main(void)
{
LinkList L,head_n,head_m;
int n,m,t,length;
L = CreateList_H();
length = getLength(L);
printList(L);
n = posInput(length);
m = posInput(length);
if(n>m)
{
t = n;
n = m;
m = t;
}
head_n = findPoint(L,n);
head_m = findPoint(L,m);
swapPoint(L,head_n,head_m);
printList(L);
return 0;
}

int posInput(int n)
{
int num;
printf("请输入你要交换的结点编号,");
printf("结点编号应该大于0,小于%d\n",n);
scanf("%d",&num);
while(num<=0 || num>n)
{
printf("结点编号应该大于0,小于%d\n",n);
scanf("%d",&num);
}
return num;
}

int getLength(LinkList head)
{
int len = 0;
LinkList p = head->next;
while(p!=NULL)
{
len++;
p = p->next;
}
return len;
}
LinkList CreateList_H()
{
int n = 0;
LinkList L = (LinkList)malloc(sizeof(node));
L->next = NULL;
LinkList p = L;
printf("创建几个结点:");
scanf("%d",&n);
for(int i=0; i<n; ++i)
{
LinkList pNew = (LinkList)malloc(sizeof(node));
printf("输入第%d个节点data值:",i+1);
scanf("%d",&pNew->data);
pNew->pos = i+1;
pNew->next = NULL;
p->next = pNew;
p = pNew;
}
return L;
}

void printList(LinkList L)
{
LinkList p = L->next;
while(p!=NULL)
{
printf("结点%d,data = %d  \n",p->pos,p->data);
p = p->next;
}
}

void swapPoint(linkNode head,linkNode node1,linkNode node2){

linkNode prenode1 = NULL;  //待交换节点node1的前一个节点
linkNode postnode1 = NULL; //待交换节点node1的后一个节点
linkNode prenode2 = NULL;  //待交换节点node2的前一个节点
linkNode postnode2 = NULL; //待交换节点node2的后一个节点

//头节点不交换
if (node1 == head || node2 == head){
return;
}

//相同不需交换
if (node1 == node2){
return;
}

prenode1 = findPre(head,node1);
prenode2 = findPre(head,node2);
postnode1 = node1->next;
postnode2 = node2->next;
//节点相邻情况处理
if (postnode1 == node2){
prenode1->next = node2;
node2->next = node1;
node1->next = postnode2;
return;
}

//其他情况下,直接交换节点
prenode1->next = node2;
node2->next = postnode1;
prenode2->next = node1;
node1->next = postnode2;
}

LinkList findPoint(const LinkList head,int pos)
{
LinkList node = head;
for(int i=1; i<=pos; i++)
{
node = node->next;
}
return node;
}

LinkList findPre(const LinkList head,const LinkList node)
{
LinkList
4000
tmp = head;
while(tmp->next!=node)
{
tmp = tmp->next;
}
return tmp;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐