01.畫圖
02.按位置查找返回元素的值
//11.按位置查找后返回元素的值
int find_pos(node_p H,int pos)
{ if(H==NULL){return -1;} if(pos<0){ return -1; } if(pos<0){ printf("查找的位置不合理.\n"); return -2; } node_p p=H->next;//從第一個數據結點開始遍歷 int i; //找到pos結點 for(i=0,p=H;i<pos;i++,p=p->next); //找到pos-1位置結點,判斷是否有pos位置 if(p==NULL){ printf("11.位置不合理.\n"); return -2; } return p->data;
}
03.按值修改(多個一樣的值修改第一個)
//12.按值修改(多個一樣的值修改第一個)
//多個值只修改第一個
void updatavalue(node_p H,int value1,int value2)
{ if(H==NULL){return;} node_p p=H->next; while(p!=NULL){ if(p->data==value1){ p->data=value2; printf("查找%d的值修改為%d的值.\n",value1,value2);return; } p=p->next; } printf("未查找到值為%d的結點,無法修改.\n",value); }
第一種情況:多個值一樣修改
//13.按值修改(多個一樣的值修改第一個)
//多個值全部修改
void updatavalue(node_p H,int value1,int value2)
{ if(H==NULL){return;} node_p p=H->next; int modified_count=0; while(p!=NULL){ if(p->data==value1){ p->data=value2; modified_count++; } p=p->next; } if(modified_count>0){ printf("成功將%d個值為%d修改為%d.\n",modified_count,value1,value2); }else{ printf("未找到值為%d的結點,無法修改.\n",value1); } }
04.單向鏈表的逆置
方法01:迭代的思想
//14.單項鏈表逆置
node_p reverseList(node_p H)
{ if(H==NULL){return NULL;} node_p prev=NULL; node_p curr=H->next; node_p next=NULL; while(curr!=NULL) { //第一步保存curr下一個結點到next指針中next=curr->next; //反轉當前結點的指針 curr->next=prev; //移動prev和curr指針 prev=curr; curr=next; } H->next=prev; return H;
}
方法02:頭插的思想
node_p reverseList(node_p H)
{ if(H==NULL){return NULL;} node_p new_head=NULL;//初始化新鏈表的頭結點 node_p current=H->next;//用于遍歷原鏈表的指針 node_p next_node;//臨時保存當前結點的下一個結點 while(current!=NULL){ next_node=current->next;//保存當前結點下一個結點 current->next=new_head;//將當前結點插入到新鏈表頭部 new_head=current;//更新新鏈表頭結點 current=next_node;//移動到原鏈表的下一個結點 } H->next=new_head; return H;//返回逆置后鏈表的頭節點 }