大华2014校园招聘面试题链式存储串的连接操作

 1 #include <stdio.h>
 2 
 3 #define N   4
 4 
 5 typedef struct Block
 6 {
 7    char buffer[N];
 8    struct Block *next;
 9 }Block;
10 
11 typedef struct
12 {
13        Block *head;
14        Block *tail;
15     int  len;
16 }BLString;
17 
18 
19 void BLStringAppend(BLString* s1, BLString* s2)
20 {
21     if(NULL == s1 || NULL == s2)//参数无效
22         return;
23     if(NULL == s1->head && NULL == s2->head)//链表都为空
24         return;
25     if(NULL == s1->head && NULL != s2->head)
26     {
27         s1->head = s2->head; //直接串2的头赋值给串1的头指针
28         return;
29     }
30     
31     s1->tail->next = s2->head;//先将s2的头和s1的尾相连接
32 
33     Block *cur_node = s1->tail;
34     Block *pnode = s2->head;
35     int cur_len = strlen(cur_node);
36     int i;
37     while(pnode != s2->tail)
38     {
39         for(i = 0; i <  N - cur_len; i++)
40         {
41             cur_node->buffer[cur_len+ i] = pnode->buffer[i];
42         }
43         for(i = 0; i < cur_len; i++)
44         {
45             pnode->buffer[i] = pnode->buffer[i+cur_len];
46         }
47         cur_node = pnode;
48         pnode = pnode->next;
49     }
50     
51     int tail_len = strlen(s2->tail->buffer);
52     if(tail_len < cur_len)
53     {
54         for(i = 0; i < tail_len; i++)
55         {
56             cur_node->buffer[cur_len+ i] = pnode->buffer[i];
57         }
58         cur_node->buffer[cur_len+i] = '\0';
59         s1->tail = cur_node;
60         cur_node->next = NULL;
61 
62         free(pnode);
63     }
64     else{
65         for(i = 0; i <  N - cur_len; i++)
66         {
67             cur_node->buffer[cur_len+ i] = pnode->buffer[i];
68         }
69         for(i = 0; i < tail_len-(N-cur_len); i++)
70         {
71             pnode->buffer[i] = pnode->buffer[i+cur_len];
72         }
73         pnode->buffer[i] = '\0';
74     }
75 }

 

posted @ 2013-12-24 17:09  夕相待  阅读(300)  评论(0编辑  收藏  举报