鏈表實現代碼
鏈表在數據結構中不難但是用的很多也算是數據結構中必須掌握的內容;數據結構學了很久了,現在寫一些也當做是回顧吧,都說數據結構重要;
每次都是,除了代碼好像就么有什么可寫的了,哎;
反正就是跟線性表類似,畢竟都是線性結構;
把原先連續的儲存單元換成了分散的節點,每一個節點分為數據域和指針域;
數據域存放數據,指針域存放下一個節點的地址,注意下一個節點在物理存儲上不一定挨著的;
我們在遍歷一個鏈表的時候是靠節點的指針域找到下一個節點的,就這樣遍歷到了所有的節點;
很多時候我們喜歡設一個頭結點(非首節點,首尾是相對的),頭結點就在首節點前面一個節點;
這個頭結點的數據域用來儲存整個鏈表的節點個數,指針域存放首節點的地址,在很多時候很方便做一些操作,更多好處百度一下就會有;
下面這個代碼我依然是加了一個頭結點:
#includeinclude
typedef struct Node
{
int data;
struct Node next;
}List;
void Initialization(List p)//初始化
{
p->data=0;
p->next=NULL;
}
void Add(List p)//添加
{
p->data++;
while(p->next!=NULL)
p=p->next;
List pNext=new struct Node;
//p=(List)malloc(sizeof(struct Node));
scanf("%d",&pNext->data );
pNext->next=NULL;
p->next=pNext;
}
void Show(List p)//輸出
{
p=p->next;
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->next;
}
}
void Insert(List p,int index,int e)//插入
{
if(index>p->data)
{
p->data++;
while(p->next !=NULL)
p=p->next;
List pNext=new struct Node;
pNext->data=e;
pNext->next=NULL;
p->next=pNext;
}
else
{
puts("2\n");
p->data++;
for(int i=0;inext;
List NEW=new struct Node;
NEW->data=e;
NEW->next=p->next;
p->next=NEW;
}
}
void Sort(List p) //排序
{
List x,y;
int len=p->data;
for(int i=0;inext;
x=p;
y=p->next;
for(int j=i+1;jdata>y->data )
x=y;
y=y->next;
}
int tmp;
if(x->data!=p->data )
{
tmp=p->data;
p->data=x->data;
x->data=tmp;
}
}
}
int main()
{
List pos;
pos=new struct Node;
Initialization(pos);
for(int i=0;i<3;++i) Add(pos); Insert(pos,2,90); Show(pos); Sort(pos); Show(pos); return 0; } //比起上篇寫的線性表加了一個排序,采用了選擇排序,其他功能和線性表差不多,如果對照起來理解的話會跟清晰;</pre>