C語言編寫一個鏈表

本文實例為大傢分享瞭C語言編寫一個鏈表的具體代碼,供大傢參考,具體內容如下

鏈表

具備的基本功能:

1.創建頭鏈表

struct Node* Creatlist(){//創建鏈表頭
 struct Node *headnode = (struct Node*)malloc(sizeof(struct Node));//創建動態內存鏈表,指針變量
 headnode->next = NULL;//鏈表初始化
 return headnode;
}

2.創建節點

struct Node* Creatnode(int num){//創建結點,鏈表,參數數字域
 struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));//創建動態內存鏈表,指針變量
 newnode->num = num;
 newnode->next = NULL;//鏈表初始化
 return newnode;
}

3.插入節點

void Insetlist(struct Node* list, int num){//頭插法
 struct Node* insetnode = Creatnode(num);
 if (list != NULL){
  insetnode->next = list->next;
  list->next = insetnode;
 }
 else{
  printf("節點不存在\n");
 }
}
void Insetlists(struct Node* headnode, int n, int num){//在n節點處插入,參數頭節點,在第n個節點處插,插入的數據num
 int i = 1;
 struct Node *t = headnode;
 while (i < n&& t!= NULL){
  t = t->next;
  i++;
 }
 if (t != NULL){
  struct Node* insetnode = Creatnode(num);
  insetnode->next = t->next;
  t->next = insetnode;
 }
 else{
  printf("節點不存在\n");
 }
}

4.修改節點

void Modifynode(struct Node* headnode, int n){//修改節點,參數鏈表,修改的第n個節點
 struct Node* list = headnode;
 int i = 0;
 while (i < n&&list != NULL){
  list = list->next;
  i++;
 }
 if (list != NULL){
  printf("請輸入你要修改的值\n");
  int j = 0;
  scanf("%d", &j);
  list->num = j;

 }
 else{
  printf("節點不存在\n");
 }
}

5.刪除節點

定義兩個指針,一個指向刪除節點的上一個節點,一個指向要刪除的節點

void Deletnode(struct Node* headnode, int n){//刪除第n個節點,
 int i = 1;
 struct Node *strat = headnode;
 struct Node *end = headnode->next;

 while (i < n&&end != NULL){
  strat = strat->next;
  end = end->next;
  i++;
 }
 if (end != NULL){
  strat->next = end->next;
  free(end);

 }
 else{
  printf("節點不存在\n");
 }
}

6.打印節點

void Printnode(struct Node* headnode){//打印節點
 struct Node* list = headnode;
 while ((list->next) != NULL){
  list = list->next;
  printf("%d\t",  list->num);
 }
 printf("\n");

}

7.主函數

int main(){
 struct Node* list = Creatlist();

 Insetlists(list, 1, 1);
 Printnode(list);
 int i = 0;
 printf("請輸入修改哪個節點\n");
 scanf("%d", &i);
 Modifynode(list, i);
 Printnode(list);
 printf("請輸入刪除哪個節點\n");
 int n = 0;
 scanf("%d", &n);
 Deletnode(list, n);
 Printnode(list);
 system("pause");
 return 0;
}

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: