?这个可以做下参考,初步测试没问题了。其他的后面写
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int val;
struct Node *next;
}Nodes, *Linklist; // 这个例子中的display函数会将遍历过的链表释放,所以看情况修改就行,仅参考
Linklist makeNode(int val){
Nodes * newNode = (Nodes *) malloc(sizeof(Nodes));
newNode->val = val;
newNode->next = NULL;
return newNode;
}
Linklist makeHead() {//头结点
Linklist head = (Linklist)malloc(sizeof(Nodes));
head->next = NULL;
return head;
}
Linklist initList(Linklist head, int val) { //头插法
if(head == NULL){ //一般这样写,只看这个函数中,如果传进来的head是个错误的,或者无效的指针,链表的头结点不存在那也没办法创建链表 //所以判空
return NULL;
}
Linklist newNode = makeNode(val);
newNode->next = head->next;
head->next = newNode;
return head;
}
Linklist deleteAtInedx(Linklist head,int index) //传入的是头指针,删除固定索引值结点
{
if(head == NULL || index < 0)
{
exit(1);
}
Linklist p = head;
if(index == 1){
head = p->next;
free(p);
return head;
}
int i = 0;
while( i < index-1 ){
if(p->next != NULL){
p=p->next;
}
printf("p = %d\n", p->val);
++i;
}
Linklist tmp = p->next;
p->next = p->next->next;
free(tmp);
return head;
}
void displayList(Linklist head) //遍历打印链表后,这里是直接将链表释放了。
{
if(head == NULL) {
exit(1);
}
while(head->next != NULL){
printf("%d ", head->next->val);
Linklist p = head->next;
head->next = head->next->next;
free(p);
}
free(head);
printf("\n");
}
Linklist insertAtTail(Linklist head, int *arr , int nums)
{
Linklist tail = head;
int i = 0;
while(i < nums)
{
Linklist newNode = makeNode(arr[i]);
tail ->next = newNode;
tail = newNode;
++i;
}
return head;
}
Linklist insertAtIndex(Linklist head , int index, int val){
if(head == NULL || index < 0){ //如果超出链表最大长度,也是可以报错处理的,因为这个案例结构中没有用链表长度,这里不写了
exit(1);
}
Linklist p = head;
Linklist tmp = makeNode(val);
for(int i=1; i < index; ++i){
p = p->next;
}
tmp->next = p->next;
p->next = tmp;
return head;
}
int main(){
int arr[] = {1,2,3,4,5,6,7};
int i = 0;
Linklist phead = makeHead();
while(i < sizeof(arr)/sizeof(int)){
phead = initList(phead,arr[i]);
i++;
}
//displayList(phead);
//Linklist phead2 = makeHead();
//phead2 = insertTail(phead2,arr,sizeof(arr)/sizeof(int));
//displayList(phead2); //
//Linklist phead3 = deleteAtIndex(phead, 1);
//displayList(phead3);
Linklist p4 =insertAtIndex(phead, 2, 9);
displayList(p4);
printf("p4 的地址是 %p\n", p4);
return 0;
}