本文目錄一覽:
c語言數據結構,單鏈表中的頭插法求解釋
L這個頭結點是不存儲數據的,L-next L的下個結點才存儲數據,為實際的第一個結點
s-next=L-next 新插入的結點s放在第一個結點前面,變為新的第一個結點,L-next=s 這句讓L-next指向新的第一個結點
L-next改為L s-next=L ,L=s可以,這樣頭指針就是實際存儲數據的第一個結點
C語言 頭插法建立鏈表
#include
stdio.h
#include
stdlib.h
typedef
struct
_list
{
int
val;
struct
_list*
next;
}
*node,
list;
//
在pos位置之後插一個節點,pos為空則在頭部插入
node
insert(
node*
head,
node
pos,
int
val
)
{
node
tmp;
tmp
=
(
node
)malloc(
sizeof(
list
)
);
tmp-val
=
val;
tmp-next
=
pos
?
pos-next
:
*head;
return
(
pos
?
pos-next
:
*head
)
=
tmp;
}
//
從數組簡單構造一個鏈表
node
create(
int*
beg,
int*
end
)
{
node
head
=
null;
while
(
beg
!=
end
)
{
insert(
head,
null,
*beg++
);
//
在頭部插入
}
return
head;
}
//
遍歷輸出各個節點的值
void
print(
node
head
)
{
while
(
head
)
{
printf(
“%d
“,
head-val
);
head
=
head-next;
}
putchar(
‘\n’
);
}
int
main()
{
int
a[]
=
{
0,1,2,3,4,5,6,7,8,9
};
node
head;
head
=
create(
a,
a
+
10
);
print(
head
);
return
0;
}
單鏈表(C語言)頭插法的建立和輸出問題
//程序有多處改動,煩請將該程序另存,對比修改前後的差別
/*
1、頭部無數據,則在鏈表中,浪費頭結點;
2、頭部有數據,則在鏈表中,浪費最後一個結點;
3、頭部無數據結點思想:將新結點掛在頭結點後面,將新數據存放在新結點中;
4、頭部有數據結點思想:將新結點掛在頭結點後面,將新數據存放在頭結點中;
*/
#include stdio.h
#include stdlib.h
#define N 5
struct Node {
int Data; /* 存儲結點數據 */
struct Node * Next; /* 指向下一個結點的指針 */
};
typedef struct Node List; /* 定義單鏈表類型 */
void headinsert(List * L);
void display( List * L );
void headinsert2(List * L);
void display2( List * L );
int main()
{
List *L1,*L2;
L1=(List *)malloc(sizeof(struct Node));
L2=(List *)malloc(sizeof(struct Node));
printf(“頭部含數據:”);
headinsert(L1);
display(L1);
printf(“\n”);
printf(“頭部含數據:”);
headinsert2(L2);
display2(L2);
printf(“\n”);
return 0;
}
void headinsert(List *L)//頭部無數據
{
int i;
List * p;
// scanf(“%d”, N);
L-Next=NULL;
for ( i=0; iN; i++ )
{
p = (List *)malloc(sizeof(struct Node));
p-Data=i+1;
p-Next = NULL;
L-Next = p; //此處有改動,否則,後面一個結點插入到前一個結點的前面了
L = L-Next ;
}
}
void display( List *L )
{
List *p;
p=L-Next;
while(p!=NULL)
{
printf(“%d “,p-Data);
p=p-Next;
}
}
void headinsert2(List *L)//頭部有數據
{
int i;
List * p;
//scanf(“%d”, N);
L-Next = NULL;
for ( i=0; iN; i++ )
{
p = (List *)malloc(sizeof(struct Node));
L-Next = p;
L-Data=i+2; //+2以示區別
L = L-Next;
p -Next = NULL;
}
}
void display2( List *L )
{
List *p;
p=L;
while(p-Next!=NULL)//此處改為p-Next!=NULL,否則會有一個垃圾數
{
printf(“%d “,p-Data);
p=p-Next;
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/154901.html