Linked List
作者:互联网
Add a node at linked list end
#include <stdio.h>
#include <stdlib.h> //malloc
typedef struct node{
int data;
struct node* next;
}*list;
list add_node_end(list ptr,int data)
{
list temp = (list*)malloc(sizeof(list));
temp -> data = data;
temp -> next = NULL;
ptr -> next = temp;
return temp;
}
int main()
{
list head = (list*)malloc(sizeof(list));
head -> data = 0;
head -> next = NULL;
list ptr = head;
ptr = add_node_end(ptr, 1);
ptr = add_node_end(ptr, 2);
ptr = add_node_end(ptr, 3);
ptr = head;
//traversing the linked list,and print the data of node
while (ptr != NULL)
{
printf("%d ",ptr -> data);
ptr = ptr -> next;
}
return 0;
}
Output:
0 1 2 3
Inserting node at the beginning of the list
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node* next;
}*list;
list add_node_end(list ptr,int data)
{
list temp = (list*)malloc(sizeof(list));
temp -> data = data;
temp -> next = NULL;
ptr -> next = temp;
return temp;
}
list add_node_begin(list ptr,int data)
{
list temp = (list*)malloc(sizeof(list));
temp -> data = data;
temp -> next = ptr;
ptr = temp;
return ptr;
}
int main()
{
list head = (list*)malloc(sizeof(list));
head -> data = 0;
head -> next = NULL;
list ptr = head;
ptr = add_node_end(ptr, 1);
ptr = add_node_end(ptr, 2);
ptr = add_node_end(ptr, 3);
ptr = add_node_begin(head, -1);
ptr = add_node_begin(ptr, -2);
while (ptr != NULL)
{
printf("%d ",ptr -> data);
ptr = ptr -> next;
}
return 0;
}
Output:
-2 -1 0 1 2 3
version 2.0
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node* next;
}*list;
list add_node_end(list ptr,int data)
{
list temp = (list*)malloc(sizeof(list));
temp -> data = data;
temp -> next = NULL;
ptr -> next = temp;
return temp;
}
void add_node_begin(list *ptr,int data)
{
list temp = (list*)malloc(sizeof(list));
temp -> data = data;
temp -> next = *ptr;
*ptr = temp;
}
int main()
{
list head = (list*)malloc(sizeof(list));
head -> data = 0;
head -> next = NULL;
list ptr = head;
ptr = add_node_end(ptr, 1);
ptr = add_node_end(ptr, 2);
ptr = add_node_end(ptr, 3);
add_node_begin(&head, -2);
add_node_begin(&head, -3);
ptr = head;
while (ptr != NULL)
{
printf("%d ",ptr -> data);
ptr = ptr -> next;
}
return 0;
}
Output:
-3 -2 0 1 2 3
标签:node,temp,List,list,ptr,add,data,Linked 来源: https://www.cnblogs.com/sixiaoxiaoya/p/16472309.html