生活随笔
收集整理的這篇文章主要介紹了
C语言 链表创建及操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C語言 鏈表創建及操作
- 第一部分構建鏈表,定義結構體,分別用頭插法、尾插法實現,這里封裝了打印函數:printf();做練習方便后續使用;對鏈表進行查找,并將查找到的值構建一個新的鏈表;鏈表的轉置;具體代碼如下:
#include<stdio.h>
#include<stdlib.h>
struct node
{int data
; struct node *next
;
};
void print_data(struct node *inc
)
{printf("data = %d\n",inc
->data
);
}
void traverse(struct node *inc
, void(*print
)(struct node *))
{while(inc
){print(inc
);inc
= inc
->next
;}
}
void insertHead(struct node **inc
, int n
)
{struct node *tmp
= malloc(sizeof(struct node));tmp
->data
= n
;tmp
->next
= *inc
;*inc
= tmp
;
}
void insertTail(struct node **inc
, int n
)
{struct node *tmp
= malloc(sizeof(struct node));tmp
->data
= n
;tmp
->next
= NULL;while(*inc
){inc
= &(*inc
)->next
;}*inc
= tmp
;
}
struct node *findNode(struct node **inc
, int goal
)
{struct node *newlist
= NULL; struct node *tmp
= *inc
; struct node *pre
; struct node *cur
; while(tmp
->next
){if(goal
== tmp
->next
->data
){pre
= tmp
;cur
= tmp
->next
;tmp
->next
= cur
->next
;cur
->next
= newlist
;newlist
= cur
;}else if(goal
== tmp
->data
){*inc
= (*inc
)->next
;tmp
->next
= newlist
;newlist
= tmp
;tmp
= *inc
;}else{tmp
= tmp
->next
;}}return newlist
;
}
void transNode(struct node **inc
)
{struct node *cur
= *inc
;struct node *pre
= NULL;struct ndoe *tmp
;while(*inc
){tmp
= cur
->next
;cur
->next
= pre
;pre
= cur
;cur
= tmp
;}*inc
= pre
;
}
int main()
{struct node *p
= NULL;insertHead(&p
,10);insertHead(&p
,20);insertHead(&p
,10);insertHead(&p
,30);insertHead(&p
,10);insertHead(&p
,40);printf("_____create list_____\n");traverse(p
,print_data
);printf("_____old list_____\n");struct node *ret
= findNode(&p
, 10);traverse(p
,print_data
);printf("_____new list_____\n");traverse(ret
,print_data
);return 0;
}
總結
以上是生活随笔為你收集整理的C语言 链表创建及操作的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。