1.創建一個節點,并將鏈表的首節點返回
創建一個獨立節點,沒有和原鏈表產生任何關系
#include "head.h"typedef struct Node
{
int num;
struct Node*pNext;
struct Node*pPer;
}NODE;
后續代碼:
NODE*createNode(int value)
{NODE*new node=(NODE*)malloc(sizeof(NODE));if(NULL==new node){perror("createNode malloc fail");return NULL;}new node->num=value;new node->pNext=NULL;new node->pPer=NULL;return new node;
}
//頭插法
NODE*instetHead(NODE*head,int value)
{NODE*new node=createNode(value);if(NULL==new code){//新節點創建失敗return head;}if(head==NULL){//原鏈表為空return new node;}new node->pNext=head;head->pPer=new node;return new node;
}
//獲取鏈表的尾節點指針
NODE*getListTail(NODE*head)
{if(head==NULL){return NULL;}while(head->pNext!=NULL){head=head->pNext;}return head;
}NODE*currentPosNOde(NODE*head,int pos)
{if(head==NULL){return NULL;}for(int i=0;i<pos-1;i++){head=head->pNext;}return head;
}
//pos=0時為頭插法
//當前函數不處理頭插和尾插的情況
NODE*insertMid(NODE*head,int value,int pos)
{NODE*new node=createNode(value);if(NULL==new node){//新節點創建失敗return head;}if(head==NULL){//原鏈表為空return new node;}
//獲取pos位置的節點指針
NODE*cur=currentPosNode(head,pos);
//將新節點與其插入位置之后的節點進行連接
new node->pNext=cur->pNext;
cur->pNext->pPer=cur;return head;