zoukankan      html  css  js  c++  java
  • [Interview] Bubble sort using singly-linked list

    • Question : 
      • Bubble sort using singly-linked list
      • 群暉面試題
    • Idea : 
      • 在linked list 交換node與node時, 我們會想用換*next的方式。但是這裡是singly-linked list.
        還會需要previously node。其實這裡單純直接換int val還比較簡單。不過算蠻偷吃步的
    • Code : [根本就是array版]
    • typedef struct Node{
          int val;
          struct Node *next;
      }Node, *NodePtr;
      void bubbleSort(NodePtr head) {
          int i,j,tmp;
          bool flag;
          for(i = 0; i < len-1 ;i++) {
              NodePtr curr = head;
              NodePtr next = head->next;
              flag = false;
              for(j=0; j < len-i-1 ;j++) {
                  if(curr->val > next->val ) {
                      tmp = curr->val;
                      curr->val = next->val; 
                      next->val = tmp;
                      flag = true;
                  }
              }
              if(flag == false) break; // 沒有結點需要swap
          }
      }
      
    •   [修改*next 版]
    void bubbleSort(NodePtr head) {
    	bool flag = true;
    	while(flag) {
    		flag = false;
    		NodePtr curr = head;
    		NodePtr prev = NULL;
    		while(curr->next){
    			if(curr->val > curr->next->val) {
    				flag = true;
    				curr = swap(curr,curr->next);
    				if(prev == NULL) //while swaping the head node
    					head = curr;
    				else
    					prev->next = curr;
    			}
    			prev = curr;
    			curr = curr->next;
    		}
    	}
    }
    

        [使用dummyHead版] - 可以減少一個if, 來判斷swap頭結點的情況。

    void bubbleSort(NodePtr head) {
    	bool flag = true;
    	NodePtr dummyHead = (NodePtr)malloc(sizeof(Node));
    	dummyHead->next = head;
    	while(flag) {
    		flag = false;
    		NodePtr curr = dummyHead->next;
    		NodePtr prev = dummyHead;
    		while(curr->next){
    			if(curr->val > curr->next->val) {
    				flag = true;
    				prev->next = curr = swap(curr,curr->next);
    			}
    			prev = curr;
    			curr = curr->next;
    		}
    		printf("flag:%d ",flag);
    		print_all(dummyHead->next);
    	}
    }
    

      

    • 完整測資 : https://github.com/bittorrent3389/leetCode/blob/master/BubbleSort.c

  • 相关阅读:
    css 边框添加四个角效果
    PS 怎么去掉噪点
    Packet Tracer——添加温度计
    zabbix监控mysql数据
    日常检测
    mysql的基本命令操作
    判断字典中是否有这个单词
    批量创建用户
    检测局域网ip存活状态
    spring boot gradle build:bootRepackage failed
  • 原文地址:https://www.cnblogs.com/bittorrent/p/4736662.html
Copyright © 2011-2022 走看看