链表的逆置和链表的合并代码实现

1.将一个单链表逆置。


#include <stdio.h> #include <malloc.h> typedef struct node { char name[20]; struct node *link; }stud; stud* reverseList(stud *head) { if(NULL == head) { return NULL; } stud *p, *q, *r; p = head; q = p->link; while(q->link != NULL) { r = q->link; q->link = p; p = q; q =r; } free(q); head->link = NULL; head = p; return head; } int main(int argc, char **argv) { stud *head = (stud*)malloc(sizeof(stud)); stud *p = head; scanf("%s", p->name); while( strcmp(p->name, "-1") ) { p->link = (stud*)malloc(sizeof(stud)); p = p->link; scanf("%s", p->name); } head = reverseList(head); p = head; while(p) { printf("%s/n", p->name); p = p->link; } p = head->link; while(p) { free(head); head = p; p = p->link ; } free(head); // system("PAUSE"); return 0; }

 

2.将两条有序的单链表合并成一条有序的单链表。

 

#include <iostream> using namespace std; /* 单链表节点 */ struct node { int value; struct node* next; }; /* 给单链表添加节点 */ void insertNode(node* head, int value) { node* p = head->next; if ( p == NULL ) { p = new node; p->value = value; p->next = NULL; head->next = p; return; } while ( p->next != NULL ) { p = p->next; } node* tmp = new node; tmp->value = value; tmp->next = NULL; p->next = tmp; } /* 遍历输出链表节点 */ void print(node* head) { node* p = head->next; while ( p != NULL ) { cout << p->value << " "; p = p->next; } cout << endl; } /* 利用一般的方法进行合并,形成整体递增有序 */ node* formalMerge(node* headA, node* headB) { node* head = new node; head->next = NULL; node* p = headA->next; node* q = headB->next; if ( p == NULL ) { return headB; } if ( q == NULL ) { return headA; } while ( (p != NULL) && (q != NULL) ) { if ( p->value == q->value ) { insertNode(head, p->value); insertNode(head, q->value); p = p->next; q = q->next; } else if ( p->value < q->value ) { insertNode(head, p->value); p = p->next; } else if ( p->value > q->value ) { insertNode(head, q->value); q = q->next; } } while ( p != NULL ) { insertNode(head, p->value); p = p->next; } while ( q != NULL ) { insertNode(head, q->value); q = q->next; } return head; }

你可能感兴趣的:(struct,qq,null)