Insert an item into a Circular Linked List
int insert_circular(node **head, int data)
{
node *p1;
node *new = (node*)malloc(sizeof(node));
new->value = data;
if (*head == NULL) {
*head = new;
*head->next = *head;
return new->value;
}
p1 = *head;
while (p1->next != *head) {
p1 = p1->next;
}
p1->next = new;
new->next = *head;
*head = new;
return new->value;
}
Insert an item into a Double Linked List
int insert_double(node** head, int num)
{
node *p0, *p1, *p2;
p2 = (node*)malloc(sizeof(node));
p2 -> data = num;
if (*head == null) {
*head = p2;
p2->prev = null;
return num;
}
p1 = *head;
while (p1 != NULL && p1->data > num) {
p0 = p1;
p1 = p1->next;
}
if (p1 == *head) { // Special Case!
p2->next = p1;
p2->prev = NULL;
*head = p2;
}
else {
p0->next = p2;
p2->prev = p0;
p2->next = p1;
if (p1 != NULL)
p1->prev = p2;
}
return num;
}
Delete an item in a Linked List
Node* Remove(Node *head, int value)
{
Node *p0, *p1, *temp;
p1 = head;
while (p1 != NULL && p1->data != value) {
p0 = p1;
p1 = p1->next;
}
if (p1 == NULL) { // Special Case! can't find
printf("can't find item\n");
}
else if (p1 == head) { Special Case! find out at head
head = head->next;
free(p1);
}
else {
p0->next = p1->next;
free(p1);
}
return head;
}
Reverse a Linked List: Ex. 1->7->5->3->Null => 3->5->7->1->Null
Node* Reverse(Node* head)
{
Node *p0, *p1, *temp;
p0 = NULL;
p1 = head;
while (p1 != NULL) {// reverse linked list
temp = p1->next;// you could draw a linked list on paper,
p1->next = p0; // to understand why it reverses the list.
p0 = p1;
p1 = temp;
}
return p0;
}
沒有留言:
張貼留言