循环链表的插入和删除
生活随笔
收集整理的這篇文章主要介紹了
循环链表的插入和删除
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
循環鏈表可以用來使計算機處理內存工作區或輸出至數據緩沖區。
循環鏈表的插入和刪除
#include"iostream"#include"stdlib.h"
using namespace std;
struct clist
{
int data;
struct clist *next;
};
typedef struct clist cnode;
typedef cnode *clink;
/*-----循環鏈表的輸出------*/
void printclist( clink head)
{
clink ptr;
head=head->next;
ptr=head;
do
{
printf("[%d]",ptr->data);
ptr=ptr->next;
}while(head!=ptr && head !=head->next);
printf("\n");
}
/*-----循環鏈表的結點插入----*/
clink insertnode(clink head,clink ptr,int value)
{
clink new_node;
new_node=(clink) malloc(sizeof(cnode));
if(!new_node)
return NULL;
new_node->data=value;
new_node->next=NULL;
if(head==NULL)
{
new_node->next=new_node;
return new_node;
}
if(ptr==NULL)
{
/*----情況1:插在第一結點之前---*/
new_node->next=head->next;
head->next->next=new_node;
}
else
{
/*-----情況2:插在結點之后-------*/
new_node->next=ptr->next;
ptr->next=new_node;
}
if(ptr==head)
head=new_node;
return head;
}
/*---循環鏈表結點刪除---*/
clink deletenode(clink head,clink ptr)
{
clink previous;
if(head==NULL)
{
/*----情況1:刪除第一個結點----*/
head->next=ptr->next;
}
else
{
/*--情況2:刪除中間結點---*/
previous=head;
if(head!=head->next)
while(previous->next!=ptr)
previous=previous->next;
previous->next=ptr->next;
}
if(ptr==head)
head=previous;
free(ptr);
return head;
}
/*使用插入結點的方式來創建鏈表,完成后將鏈表內容輸出,然后刪除前后兩結點*/
int main()
{
clink head=NULL;
int list[6]={9,7,3,4,5,6};
int i;
head=insertnode(head,head,list[0]);
printf("創建第一個結點: ");
printclist(head);
/*---情況1:插在第一結點前----*/
head=insertnode(head,NULL,list[1]);
printf("插入第一結點之前: ");
printclist(head);
for(i=2;i<6;i++)
{
/*---情況2:插在結點之后-----*/
head=insertnode(head,head->next,list[i]);
printf("插入結點之后: ");
printclist(head);
}
/*---情況1:刪除第一個結點---*/
head=deletenode(head,head->next);
printf("刪除第一個結點: ");
printclist(head);
/*--刪除最后一個結點--*/
printf("刪除最后一個結點: ");
head=deletenode(head,head);
printclist(head);
}
?
轉載于:https://www.cnblogs.com/FCWORLD/archive/2010/11/20/1882463.html
總結
以上是生活随笔為你收集整理的循环链表的插入和删除的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用ASP.NET 2.0提供的WebR
- 下一篇: Java虚拟机详解(六)------内存