Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * linkedlistv2.c
- *
- * Created on: May 29, 2015
- * Author: trongkha
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct node {
- int data;
- struct node* next;
- };
- void show_list(struct node* head) {
- struct node* current = head;
- while (current != NULL) {
- printf("data: %d \n", current->data);
- current = current->next;
- }
- }
- void Push(struct node** headRef, int data) {
- struct node* newNode = malloc(sizeof(struct node));
- newNode->data = data;
- newNode->next = *headRef; // The '*' to dereferences back to the real head
- *headRef = newNode;
- }
- void insert_after(struct node* head, struct node* inserted_node, int position) {
- struct node* left = NULL;
- struct node* current = head;
- if (head == NULL)
- return;
- int i = 0;
- for (i = 0; i <= position; i++) {
- left = current;
- current = current->next;
- }
- left->next = inserted_node;
- inserted_node->next = current;
- }
- void clone_node(struct node* head, int node_position, int times) {
- int i = 0;
- struct node* current = head;
- if (head == NULL)
- return;
- // move to node clone
- for (i = 0; i < node_position; i++) {
- current = current->next;
- }
- // clone times
- for (i = 0; i < times; i++) {
- struct node* node_clone = malloc(sizeof(struct node));
- memcpy(node_clone, current, sizeof(struct node));
- insert_after(head, node_clone, node_position);
- }
- }
- struct node* build_node() {
- struct node* head = NULL;
- int i = 0;
- for (i = 0; i < 3; i++) {
- Push(&head, i);
- }
- return head;
- }
- int main() {
- struct node* head = build_node();
- show_list(head);
- printf("======================\n");
- int weight[3] = { 2, 1, 4 };
- int i = 0;
- for (i = 0; i < 3; i++) {
- if (i == 0) {
- clone_node(head, 0, weight[0]);
- } else {
- int j = 0;
- int sum_weight = 0;
- for (j = 0; j <= i - 1; j++) {
- sum_weight += weight[j];
- }
- clone_node(head, i + sum_weight, weight[i]);
- }
- }
- show_list(head);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement