Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- typedef struct _node {
- char data[64];
- struct _node *next;
- } node;
- node *addNode(node *head)
- {
- node * el = head;
- node * n = (node*) malloc(sizeof(node));
- n->next = NULL;
- printf("input data: "); scanf("%s", n->data);
- if (head)
- {
- while (el->next)
- el = el->next;
- el->next = n;
- return head;
- }
- else
- {
- return n;
- }
- }
- void removeNode(node **head, node *del)
- {
- node *el = *head;
- if (*head == del)
- {
- *head = del->next;
- }
- else
- {
- while (el->next && el->next != del)
- el = el->next;
- if (!el->next) return;
- el->next = del->next;
- }
- free(del);
- }
- node *getNodeById(node *head, int pos)
- {
- int i;
- char flag;
- node *lim = head, *found = head;
- flag = pos >= 0 ? 1 : -1;
- pos *= flag;
- for (i = 0; lim; i++, lim = lim->next)
- {
- if (flag == 1 && i >= pos)
- {
- found = lim;
- break;
- }
- else if (flag == -1 && i >= pos)
- found = found->next;
- }
- if (i < pos) return NULL;
- else return found;
- }
- void printList(node *head)
- {
- node *el = head;
- while (el)
- {
- printf("%s\n", el->data);
- el = el->next;
- }
- }
- int main()
- {
- int n, i, fi;
- node *head = NULL, *f = NULL;
- printf("input n: "); scanf("%d", &n);
- for (i = 0; i < n; i++)
- {
- head = addNode(head);
- }
- printf("Input position: "); scanf("%d", &fi);
- f = getNodeById(head, fi);
- if (f)
- printf("Founded = %s\n", f->data);
- else
- printf("Error: list index out of range.\n");
- printList(head);
- printf("\n---REMOVE---\n");
- removeNode(&head, head);
- printList(head);
- _getch();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment