只要知道指針的作用就課以簡單理解:
#include<iostream>
using namespace std;
struct node
{
int date;
node *next;
}
node *p,*r,*head;
int main()
{
int x;
cin >> x;
head = new node;//申請頭結點
while(x!=0)//讀入不等於0的數
{
p = new node;//申請一個新的結點
p->date = x;
p->next=NULL:
r->next = p;//把新節點與前面的節點相連
r = p;//為指針向后移動
cin >> x;
}
p = head->next;//頭指針沒有數據,所以從第一個開始就好了
while(p->next!=NULL)//因為最后一個指針是空指針。
{
cout<<p->date<<" ";
p=p->next;
}
cout<<p->date<<endl;//輸出最后接結點的值也可以用do while語句
return 0;
}
單鏈表的操作
1,查找滿足一定條件的數據,
p = head->next;//頭指針沒有數據,所以從第一個開始就好了
while(p->next!=NULL)//因為最后一個指針是空指針。
{
if();//寫滿足條件的數據,並處理它;
p=p->next;
}
2,取出鏈表中的第i個數據;
p = head->next;//頭指針沒有數據,所以從第一個開始就好了
while(p->next!=NULL&&j<i)//因為最后一個指針是空指針。
{
p=p->next;
j++;
}
3,插入一個結點單鏈表中
//核心代碼
void insert(node *head,int i,int x)//插入元素到第i個元素之前
{
node *p,*s;
int j;
p = head;
j = 0;
while( p->next != NULL && j < i-1)
{
p = p->next;
j++;
}
if(p == NULL)//也就是到尾結點也沒有找到
puts("no answer!");
else
{
s = new node;
s->date = x;
s->next = p->next;//交換地址插入
p->next = s;
}
}
4,刪除單鏈表的元素
//將上面添加結點的else換成如下代碼
s = p->next;//將結點拿出
p->next = s->next;//p->next = p->next->next;//將鏈條和成一天去掉一定的位置的結點
free(s);//釋放空間,
5,長度的遍歷加1
就行了