链表结点移动

来源:互联网 发布:外贸翻译软件 编辑:程序博客网 时间:2024/05/12 05:00

将已知链表中元素值最小的结点移到第一个结点,来看代码:

#include "stdafx.h"#include <stdio.h>#include <iostream>using namespace std;//定义结构体类型Ptypedef struct point{int data;struct point *next;//指向结构体的指针}P;//创建链表(指定长度,存在结构体数组中),返回头指针P *createlink(P a[],int n){P *head=&a[0];for(int i=0;i<n-1;i++){a[i].next=&a[i+1];}a[n-1].next=NULL;return head;}//链表输出void output(P *head){P *ph=head;while(ph!=NULL){cout<<ph->data<<'\t';ph=ph->next;}}//找出最小的那个元素并返回int find_min(P *head){P *p=head;int dat=p->data;p=p->next;while(p!=NULL){if(p->data<dat){dat=p->data;}p=p->next;}return dat;}//移动最小元素的结点到链表头P *move_head(P *head,int dat){P *p=head,*front;while(p!=NULL){if(dat==p->data)break;front=p;p=p->next;}if(p!=NULL&&p!=head){front->next=p->next;p->next=head;head=p;}else if(p==head)//只有一个元素,或者第一个元素就是最小的{head=p;}return head;}int main(){P a[8]={{10},{1},{12},{15},{6},{9},{4},{0}},*head;head=createlink(a,8);printf("未改变的链表数据如下:\n");output(head);printf("\n====================\n");int dat=find_min(head);cout<<"The minimun data is "<<dat<<endl;head=move_head(head,dat);printf("改变后的链表数据如下:\n");output(head);cout<<endl;system("pause");return 0;}

输出结果显示:


0 0
原创粉丝点击