11#include <stdio.h>
22#include <stdlib.h>
3+ #include <stdbool.h>
34#include <string.h>
45
56#define container_of (ptr , type , member ) \
910 container_of(ptr, type, member)
1011
1112#define list_first_entry (ptr , type , field ) list_entry((ptr)->next, type, field)
12- #define list_last_entry (ptr , type , field ) list_entry((ptr)->prev, type, field)
1313
1414#define list_for_each (p , head ) \
1515 for (p = (head)->next; p != (head); p = p->next)
1616
17- #define list_for_each_safe (p , n , head ) \
18- for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next)
19-
2017struct list_head {
2118 struct list_head * next , * prev ;
2219};
@@ -78,11 +75,11 @@ static int BKDRHash(char* str, int size)
7875 return hash % size ;
7976}
8077
81- static struct word_node * find (char * word , struct list_head * hheads , int size )
78+ static struct word_node * find (char * word , struct list_head * dict , int size )
8279{
8380 struct list_head * p ;
8481 int hash = BKDRHash (word , size );
85- list_for_each (p , & hheads [hash ]) {
82+ list_for_each (p , & dict [hash ]) {
8683 struct word_node * node = list_entry (p , struct word_node , node );
8784 if (node -> step == 0 && !strcmp (node -> word , word )) {
8885 return node ;
@@ -98,18 +95,25 @@ static int ladderLength(char* beginWord, char* endWord, char** wordList, int wor
9895 struct list_head queue ;
9996 struct word_node * node ;
10097
101- struct list_head * hheads = malloc (wordListSize * sizeof (* hheads ));
98+ struct list_head * dict = malloc (wordListSize * sizeof (* dict ));
10299 for (i = 0 ; i < wordListSize ; i ++ ) {
103- INIT_LIST_HEAD (hheads + i );
100+ INIT_LIST_HEAD (dict + i );
104101 }
105102
106103 /* Add into hash list */
104+ bool found = false;
107105 for (i = 0 ; i < wordListSize ; i ++ ) {
108106 node = malloc (sizeof (* node ));
109107 node -> word = wordList [i ];
110108 node -> step = 0 ;
111109 int hash = BKDRHash (wordList [i ], wordListSize );
112- list_add (& node -> node , & hheads [hash ]);
110+ list_add (& node -> node , & dict [hash ]);
111+ if (!strcmp (endWord , wordList [i ])) {
112+ found = true;
113+ }
114+ }
115+ if (!found ) {
116+ return 0 ;
113117 }
114118
115119 /* FIFO */
@@ -127,8 +131,9 @@ static int ladderLength(char* beginWord, char* endWord, char** wordList, int wor
127131 for (c = 'a' ; c <= 'z' ; c ++ ) {
128132 if (c == o ) continue ;
129133 word [i ] = c ;
130- node = find (word , hheads , wordListSize );
134+ node = find (word , dict , wordListSize );
131135 if (node != NULL ) {
136+ /* enqueue */
132137 list_add_tail (& node -> link , & queue );
133138 node -> step = first -> step + 1 ;
134139 }
@@ -139,6 +144,7 @@ static int ladderLength(char* beginWord, char* endWord, char** wordList, int wor
139144 if (list_empty (& queue )) {
140145 return 0 ;
141146 } else {
147+ /* dequeue */
142148 first = list_first_entry (& queue , struct word_node , link );
143149 list_del (& first -> link );
144150 }
0 commit comments