Skip to content

Instantly share code, notes, and snippets.

@ta1hia
Created November 7, 2015 20:08
Show Gist options
  • Save ta1hia/e0796061fcb0d830c770 to your computer and use it in GitHub Desktop.
Save ta1hia/e0796061fcb0d830c770 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
struct Node *prev;
struct Node *next;
int data;
} Node;
int insertAtHead(Node **head, int data) {
Node *newHead = malloc(sizeof(Node));
if (!newHead) return 1;
newHead->data=data;
newHead->next=*head;
(*head)->prev=newHead;
*head=newHead;
return 0;
}
Node* find(Node** head, int target) {
Node *cur = malloc(sizeof(Node));
if (!cur) return cur;
cur = *head;
while (cur) {
if (cur->data == target) break;
cur = cur->next;
}
return cur;
}
int deleteNode(Node **head, Node *node) {
if (!node || !head) return 1;
if (*head == node) {
*head = node->next;
node->next->prev = *head;
} else {
Node *adj = malloc(sizeof(Node));
if (!adj) return 1;
adj = node->prev;
adj->next = node->next;
adj = node->next;
if (adj) adj->prev = node->prev;
}
free(node);
return 0;
}
//assume singly linked
int reverseList(Node **head) {
if (!head && !*head) return 1;
Node *cur = malloc(sizeof(Node));
Node *next = malloc(sizeof(Node));
Node *temp = malloc(sizeof(Node));
cur = *head;
next = cur->next;
while (next) {
temp = next->next;
next->next = cur;
cur = next;
next= temp;
}
(*head)->next = NULL;
*head = cur;
return 0;
}
void printList(Node *node) {
if (!node) return;
Node *cur = malloc(sizeof(Node));
if (!cur) return;
cur = node;
while (cur) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment