您的位置:首页 > 其它

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

2016-12-01 02:51 369 查看
单链表

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

struct Node{
int num;
struct Node *next;
};
typedef struct Node * PNODE;

PNODE Create()/*创建链表*/
{
PNODE phead = (PNODE)malloc(sizeof(struct Node));
phead->next = NULL;

PNODE PTlie = phead;
int lenth,number;
scanf("%d",&lenth);
printf("输入数字:");
for(int i = 0; i < lenth; i++)
{
PNODE pnew = (PNODE)malloc(sizeof(struct Node));
scanf("%d",&number);
pnew->num = number;
pnew->next =NULL;
PTlie->next = pnew;
PTlie = pnew;
}

return phead;
}
/*交换*/
void swap(PNODE p,int n)/*交换是当前位置和后面一个位置交换*/
{
int i = 0;
while(i != n - 1 && p->next != NULL)/*记录要交换结点的前一个结点*/
{
p = p->next;
i++;
}
if(p->next == NULL)
{
printf("no\n");
return ;
}

PNODE p1,p2;/*定义p1,p2分别记录要交换两个结点*/
p1 = p->next;
p2 = p1->next;

p1->next = p2->next;
p->next = p2;
p2->next = p1;
}

void print(PNODE p)
{
p = p->next;
for(int i = 0;p != NULL; i++)
{
printf("%d ",p->num);
p = p->next;
}
printf("\n\n");
}

int main(void)
{
PNODE p = Create();
int n;
printf("输入要交换的位置:");
scanf("%d",&n);/*交换是当前位置和后面一个位置交换*/

print(p);

swap(p,n);

print(p);
return 0;
}

双链表
#include<stdio.h>
#include<stdlib.h>

struct Node{
int num;
struct Node * next;
struct Node * last;
};
typedef struct Node * PNODE;
int lenth;

PNODE Create()/*创建一个双向循环链表*/
{
PNODE phead = (PNODE)malloc(sizeof(struct Node));
phead->next = phead;
phead->last = phead;

PNODE PTlie = phead;
int number;
scanf("%d",&lenth);
for(int i = 0; i < lenth; i++)
{
PNODE pnew = (PNODE)malloc(sizeof(struct Node));
scanf("%d",&number);
pnew->num = number;
pnew->next = phead;

pnew->last = PTlie;
PTlie->next = pnew;
PTlie = pnew;
}
return phead;
}

void swap(PNODE p,int n)/*交换是当前位置和后面一个位置交换*/
{
int i = 0;

while(i != n - 1 && p->next != NULL)/*记录要交换结点的前一个结点*/
{
p = p->next;
i++;
}

PNODE p1,p2;/*定义p1,p2分别记录要交换两个结点*/

p1 = p->next;
p2 = p1->next;

p1->next = p2->next;
p2->next->last = p1;/*这里注意,如果是双向不循环链表的话,最后两个数交换,会导致程序错误。因为p2->next为空*/

p->next = p2;
p2->last = p;

p2->next = p1;
p1->last = p2;

}

void print(PNODE p,int lenth)
{
p = p->next;
for(int i = 0; i < lenth; i++)
{
printf("%d ",p->num);
p = p->next;
}
printf("\n\n");
}

int main(void)
{
PNODE p = Create();

int n;
scanf("%d",&n);

print(p,lenth);

swap(p,n);

print(p,lenth);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐