尋找鏈表中值域最小的節點並移到鏈表的最前面

一、題目描述

        已知線性鏈表由list指出,鏈節點的構造爲(data,next),請寫一個算法,將鏈表中數據域值最小的那個節點移動到鏈表的最前面。(不能申請額外的節點)(更好的閱讀體驗,請訪問程序員在旅途

二、分析解答

        主要解題思路就是,遍歷鏈表,找到最小的那個節點min,以及該節點的前驅pre_min,然後將其移到鏈表的最前面。
        值得注意的是,由於節點結構要求的是單向單鏈表,因此,如果要移動min,必須要找到他的前驅。如果是雙向鏈表,就可以不用記錄前驅結點了。

int move_min_to_first(PNode head){
  PNode pre_p = head->next, p = pre_p->next;
  //將最小的元素節點及其前驅記錄下來
  PNode pre_min = head, min = pre_p;
  //判斷鏈表是否爲空
  if(head == NULL || head->next == NULL){
    return -1;
  }
  //遍歷鏈表,尋找最小元素節點
  while§{
    if(min->data > p->data){
      pre_min = pre_p;
      min = p;
    }
    pre_p = p;
    p = p->next;
  }
  //移動到鏈表的最前面
  pre_min->next = min->next;
  min->next = head->next;
  head->next = min;
  return 1;
}

    完整可執行程序代碼如下:

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

typedef struct node{

	int data;
	struct node *next;

}Node,*PNode;


/*

  方法思路:
          遍歷鏈表,找到其中最小的元素節點及其前驅結點,然後將最小的節點放置在鏈表最前面。

  返回值:
      -1 鏈表爲空,無法尋找;
	  0  查找失敗;
	  1查找成功。

*/

int move_min_to_first(PNode head){

	PNode pre_p = head->next, p = pre_p->next;
    
	//將最小的元素節點及其前驅記錄下來
	PNode pre_min = head, min = pre_p;

	//判斷鏈表是否爲空
	if(head == NULL || head->next == NULL){
	
		return -1;
	}

	//遍歷鏈表,尋找最小元素節點
	while(p){
	
		if(min->data > p->data){
		
			pre_min = pre_p;
			min = p;
		
		}

		pre_p = p;
		p = p->next;

	}

	//移動到鏈表的最前面
	pre_min->next = min->next;
	min->next = head->next;
	head->next = min;

	return 1;

}

//頭插法建立帶有頭結點的單鏈表
PNode creat_list(){
 
	//申請頭結點
	PNode head = (PNode)malloc(sizeof(Node));
 
	head->next = NULL;
	scanf("%d",&(head->data)); // 頭結點的數據域可以存放總結點數
 
	//新增元素
	PNode p =  NULL;
	int i;
	for(i=0;i<(head->data);i++){
	
		p = (PNode)malloc(sizeof(Node));
 
		scanf("%d",&(p->data));
		
		//這是頭插法的關鍵所在
		p->next = head->next;
		head->next = p;
 
	}
	return head;
 
}
 
void print_list(PNode head){
 
		PNode p = head->next;
 
		while(p){
		
			printf("p->data: %d \t",p->data);
 
			p = p->next;
		
		}
		printf("\n");
 
}
  int main(){
  
	  PNode head = creat_list();
 
	  print_list(head);
 
	  move_min_to_first(head);
 
	  print_list(head);
 
	  return 0;
  
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章