这是个很简单的链表创建和输出
#include<stdio.h>
#include<stdlib.h>
typedef struct linkednode
{
char data
struct linkednode *next
}node,*link_list//链表节点的结构及重命名
link_list creat()//创建一个链表返回类型是链表的首地址
{
link_list L
node *p1,*p2
char data
L=(node*)malloc(sizeof(node))//开辟存储空间
p2=L
while((data=getchar())!='\n')//输入回车键时结束输入
{
p1=(node*)malloc(sizeof(node))
p1->data=data
p2->next=p1
p2=p1
}
p2->next=NULL
return L
}
void print(link_list L)//把链表输出
{
node *p
p=L->next
while(p!=NULL)
{
printf("%c",p->data)
p=p->next
}
printf("\n")
}
void main()
{
link_list L=NULL
char x
printf("请输入链表节点:\n")
L=creat()
print(L)
}
#include <stdio.h> #include <stdlib.h> struct node { int data struct node * next } //建立只含头结点的空链表 struct node * create_list() { struct node * head = NULL head = (struct node *)malloc(sizeof(struct node)) if (NULL == head) { printf("memory out of use/n") return NULL } head->next = NULL head->data = 0 return head } //头插法建立链表 int insert_form_head(struct node * head, int num) { struct node * head_t = head->next struct node * new_node = NULL new_node = (struct node *)malloc(sizeof(struct node)) if (NULL == new_node) { printf("memory out of use/n") return -1 } //将新结点插入到链表的最后 new_node->data = num new_node->next = head_t head->next = new_node return 0 } //打印链表 int show_list(struct node * head) { struct node * temp temp = head->next while(temp) { printf("%d/n",temp->data) temp = temp->next } return 0 } // 按值删除结点,头结点不被删除 int delete_node(struct node *head, int data) { //head_t 保存要删除结点的上一个结点 struct node * head_t = head struct node * temp = NULL if (head == NULL) { printf("delete node from empty list!/n") return -1 } //查找删除的结点的前一个结点 //如果此处查找的是删除的结点,则需要另加一个指针保存删除结点的前一个指针 while(NULL != head_t->next) { if (data == head_t->next->data) break head_t = head_t->next } //如果要删除的结点不存在,直接返回 if (NULL==head_t->next) { printf("node not found/n") return -1 } //删除 *** 作 temp = head_t->next head_t->next = head_t->next->next free(temp) return 0 } int main(int argc, char* argv[]) { struct node * head head = create_list() if (NULL == head) printf("create_list error/n") insert_form_head(head,123) insert_form_head(head,456) show_list(head) printf("delete once!/n") delete_node(head,123) show_list(head) printf("delete second!/n") delete_node(head,456) show_list(head) delete_node(head,0) show_list(head) }欢迎分享,转载请注明来源:内存溢出
评论列表(0条)