Skip to content

Instantly share code, notes, and snippets.

@tamarous
Created July 24, 2017 08:33
Show Gist options
  • Save tamarous/73f2d0e62e07eeb6da39668265af65f4 to your computer and use it in GitHub Desktop.
Save tamarous/73f2d0e62e07eeb6da39668265af65f4 to your computer and use it in GitHub Desktop.
合并单链表-无头结点
Node *MergeLists(Node *headA, Node *headB) {
if (headA == NULL && headB == NULL) {
return NULL;
} else if (! headA && headB) {
return headB;
} else if (headA && !headB) {
return headA;
} else {
Node *ptrToA = headA, *ptrToB = headB;
Node *cur = (Node *)malloc(sizeof(Node));
Node *head = cur;
while(ptrToA && ptrToB) {
while(ptrToA && ptrToB && (ptrToA->data < ptrToB->data)) {
Node *newCell = (Node *)malloc(sizeof(Node));
newCell->data = ptrToA->data;
cur->next = newCell;
cur = newCell;
ptrToA = ptrToA->next;
}
while(ptrToA && ptrToB && (ptrToA->data > ptrToB->data)) {
Node *newCell = (Node *)malloc(sizeof(Node));
newCell->data = ptrToB->data;
cur->next = newCell;
cur = newCell;
ptrToB = ptrToB->next;
}
while(ptrToA && ptrToB && (ptrToA->data == ptrToB->data)) {
Node *newCell = (Node *)malloc(sizeof(Node));
newCell->data = ptrToA->data;
cur->next = newCell;
cur = newCell;
ptrToA = ptrToA->next;
ptrToB = ptrToB->next;
}
}
if(!ptrToA && ptrToB) {
while(ptrToB) {
Node *newCell = (Node *)malloc(sizeof(Node));
newCell->data = ptrToB->data;
cur->next = newCell;
cur = newCell;
ptrToB = ptrToB->next;
}
cur->next = NULL;
} else if(ptrToA && !ptrToB) {
while(ptrToA) {
Node *newCell = (Node *)malloc(sizeof(Node));
newCell->data = ptrToA->data;
cur->next = newCell;
cur = newCell;
ptrToA = ptrToA->next;
}
cur->next = NULL;
} else if (!ptrToA && !ptrToB ) {
cur->next = NULL;
}
return head->next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment