#include <stdio.h>
#include <stdlib.h>
#include "node.h"
int main(int argc, char *argv[]) {
printf("請輸入,結束輸入請輸入-1\n");
int temp=-1;
node* head=NULL;//一個叫head的node型變數
// node** phead=&head;
do{
scanf("%d",&temp);
head=linked_line_input(head, temp);//正常往后加,插入額外做
}while(temp!=-1);
// printf("%d",head->number);
node* temp1;
for(temp1=head;temp1;temp1=temp1->p){
printf("%d ",temp1->number);
}
linked_line_printall(head);
return 0;
}
#ifndef _NODE_H_
#define _NODE_H_
//void linked_line_input(int value);
//void linked_line_delete
//void linked_line_printall(node* head);
typedef struct linked_line_node {
int number;
struct linked_line_node* p;
}node;
node* linked_line_input(node* head, int value){
//不能用陣列,不能長大
// node* all=NULL; //全域指標
//創立一個單獨node
node* all=(node*)malloc(sizeof(node));
all->number=value;
all->p=NULL;
node* last=head;//定義最后一個
if(last->p){
while(last->p)
last=last->p;
}else
head->p=all;//遍歷last是否為0,當為0時,使之鏈到前面創立的all項
// printf("%d",all->number);
return head;
}
void linked_line_printall(node* head){
node* temp=head;
for(;temp->p;temp=temp->p){
printf("%d ",temp->number);
}
}
#endif
uj5u.com熱心網友回復:
node* linked_line_input(node* head, int value)
{
//不能用陣列,不能長大
// node* all=NULL; //全域指標
//創立一個單獨node
node* all=(node*)malloc(sizeof(node));
all->number=value;
all->p=NULL;
node* last=head;//定義最后一個
if (!last) { //第一個節點,第一個節點head為NULL,因此不能判斷last->p
head = all;
return head;
}
if(last->p) {
while(last->p)
last=last->p;
}
last->p = all;
/*
else
head->p=all;//遍歷last是否為0,當為0時,使之鏈到前面創立的all項
*/
// printf("%d",all->number);
return head;
}
鏈表插入有問題,對于第一個節點處理的不對,供參考~
int main(int argc, char *argv[])
{
printf("請輸入,結束輸入請輸入-1\n");
int temp=-1;
node* head=NULL;//一個叫head的node型變數
// node** phead=&head;
do{
scanf("%d",&temp);
if (temp < 0)
break;
head=linked_line_input(head, temp);//正常往后加,插入額外做
}while(1);
// printf("%d",head->number);
node* temp1;
for(temp1=head;temp1;temp1=temp1->p){
printf("%d ",temp1->number);
}
linked_line_printall(head);
return 0;
}
供參考
main函式里對于temp的值為1處理不合理,改一下~
uj5u.com熱心網友回復:
資料結構對單鏈表進行資料排序 http://bbs.csdn.net/topics/392201633uj5u.com熱心網友回復:
if(last->p){while(last->p)
last=last->p;
}else
head->p=all;//遍歷last是否為0,當為0時,使之鏈到前面創立的all項
上面的程式有問題,改為
if(last) {
while(last->p) last = last->p;
last->p = all;
}else head = all;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/12605.html
標籤:C語言
上一篇:遞回求解
下一篇:沒用.cpp
