部分連結串列題
阿新 • • 發佈:2018-12-10
#include <stdio.h> BOOL Insert_Last(List *ls, Data data) { if (NULL == ls) return ERROR; Node *node = (Node *)malloc(sizeof(Node)/sizeof(char)); if (NULL == node) return ERROR; node->data = data; node->next = NULL; Node *tmp = ls->head; // 頭結點 while (tmp->next) { tmp = tmp->next; } tmp->next = node; return TRUE; } void Display(List *ls) { if (NULL == ls) return; Node *tmp = ls->head->next; // 第一個結點 while (tmp) { printf ("%-4d", tmp->data); tmp = tmp->next; } printf ("\n"); } List *CreateList()//建立連結串列 { List *ls = (List*)malloc(sizeof(List)/sizeof(char)); if (NULL == ls) return NULL; // 建立頭結點 ls->head = (Node*)malloc(sizeof(Node)/sizeof(char)); if(NULL == ls->head) { free(ls); return NULL; } ls->head->next = NULL; // 空連結串列 return ls; } int OverLap(List *ls1 , List *ls2)//找兩個連結串列重合的點 { if(NULL == ls1 || NULL == ls2) return; Node *tmp1 = ls1->head; Node *tmp2 = ls2->head; Node *tmp = ls2->head; int pos1 = 1; int pos2 = 1; while(tmp1->next) { tmp1 = tmp1->next; //第一遍指向ls1的第一個結點 //printf("tmp1 = %d\n",tmp1->data); while(tmp2->next) { if(tmp1->data == tmp2->next->data) return pos1; pos2++; tmp2 = tmp2->next; //printf("pos2 = %d\n",pos2); } tmp2 = tmp; pos2 = 1; pos1++; } return pos1; } int Find_K(List *ls , int k)//找一個不知長度的連結串列的倒數第K個點 { if(NULL == ls) return; int i , count = 0; Node *tmp1 = ls->head; Node *tmp2 = ls->head; for(i = 0; i < k; i++) { tmp1 = tmp1->next; } while(tmp1->next) { tmp1 = tmp1->next; tmp2 = tmp2->next; count++; } return count; } int main() { List *ls1 = CreateList(); List *ls2 = CreateList(); if (NULL == ls1 || NULL == ls2) { printf ("建立失敗\n"); } printf ("建立成功\n"); int i; for (i = 0; i < 10; i++) { Insert_Last(ls1, i); } Display(ls1); printf("----------------\n"); Insert_Last(ls2, 3); Insert_Last(ls2, 4); Insert_Last(ls2, 7); Insert_Last(ls2, 11); Insert_Last(ls2, 12); Display(ls2); printf("----------------\n"); int a; a = OverLap(ls1 , ls2); printf("在連結串列ls1的第 %d 個位置重合\n", a); a = Find_K(ls1 , 2); printf("倒數第K個數是 %d \n", a); return 0; }