链表的遍历:
int ListLength(struct ListNode *head){
struct ListNode *current=head;
int count=0;
while(current!=NULL){
current=current ->next;
}
return count;
}
链表的插入:
void InsertInLinkedList(struct ListNode**head,int data,int position){
int k=1;
struct listNode *p,*q,*newNode;
newNode=(ListNode *)malloc(sizeof(struct ListNode));
if(!newNode){
printf("error");
return;
}
newNode->data=data;
p=*head;
//插入头部
if(position==1){
newNode->next=p;
*head=newNode;
}
else{
//插入我们想要的任意位置
while((p!=NULL)&&(k<position)){
k++;
q=p;
p=q->next;
}
q->next=newNode;
newNode->next=p;
}
}
链表的删除:
void deleteListNode(struct ListNode**head,int position){
struct ListNode *p,*q;
int k=1;
if(*head==NULL){
cout<<"List empty";
return;
}
p=*head;
if(position==1){
*head=*head->next;
free(p);
return;
}
else{
while((k<position)&&(p!=NULL)){
k++;
q=p;
p=p->next;
}
if(p==NULL)
cout<<"end";
else{
q->next=p->next;
free(p);
}
}
}
原文:https://www.cnblogs.com/gtz-gdufs/p/10663164.html