查看两个链表是否相交

来源:互联网 发布:php输出一个超链接 编辑:程序博客网 时间:2024/04/29 07:05

#define NULL 0

 

typdedef struct LinkNode {

char key;

linkNode *next;

}LinkNode;

 

unsigned int LinkNode_Length(LinkNode *pHead) {

unsigned int length = 0;

LinkNode *temp = pHead;

while(temp != pHead) {

length++;

temp = temp->next;

}

return length;

}

 

LinkNode *FirstCommonNode(LinkNode *pHead1, LinkNode *pHead2) {

unsigned int length1 = LinkNode_Length(pHead1);

unsigned int length2 = LinkNode_Length(pHead2);

 

LinkNode *linkNode1 = pHead1;

LinkNode *linkNode2 = pHead2;

 

if(length1 > length2) {

for(unsigned int i = 0; i < (length1 - length2); i++) {

linkNode1 = linkNode1->next;

}

} else {

for(unsigned int i = 0; i < length2 - length2); i++) {

linkNode2 = linkNode2->next;

}

}

 

while(linkNode1 != NULL && linkNode2 != NULL) {

if(linkNode1->key == linkNode2->key) {

return linkNode1;

}

linkNode1 = linkNode1->next;

linkNode2 = linkNode2->next;

}

return NULL;

}

 

//test function

#include <stdio.h>

#include <malloc.h>

 

LinkNode *LinkNode_Write() {

char ch;

linkNode *head = NULL;

linkNode *temp = NULL;

linkNode *str = NULL;

printf("please input the char end with enter/n");

 

while(scanf("%c", &ch) && ch != '/n') {

str = (LinkNode *)malloc(sizeof(LinkNode));

str->key = ch;

str->next = NULL;

 

if(head == NULL) {

head = str;

temp = str;

} else {

temp->next = str;

temp = str;

}

}

 

return head;

}

 

void LinkNode_Print(LinkNode *pHead) {

LinkNode *temp = pHead;

while(temp != NULL) {

printf("%c/n", temp->key);

temp = temp->next;

}

}

 

 

int main(int argc, char *argv[]) {

LinkNode *a = LinkNode_Write();

LinkNode *b = LinkNode_Write();

 

LinkNode_Print(a);

LinkNode_Print(b);

 

if(FirstCommonNode(a, b) != NULL) {

LinkNode_Print(FirstCommonNode(a, b));

} else {

printf("---error---/n"); 

}

return 0;

}

原创粉丝点击