按首字母排序字符串的链表

时间:2017-07-10 15:15:12

标签: linked-list runtime pseudocode

我无法使用以A,B,C开头的字符串对字符串的链接列表进行排序。因此,它只是一个链接列表,其中以'A'开头的所有字符串都出现在以'B'开头的所有字符串之前,所有这些都出现在以'C'开头的所有字符串之前。列表不需要进行排序,并且不需要保留以相同字母开头的字符串的相对顺序。它也需要在O(N)时间内。

我想做的方法是创建一个空的链表,然后通过给定的链表查找以A开头的所有字符串,然后将其添加到空列表中。然后再次查看给定列表中以B开头的字符串,然后将其添加到空列表中。我不确定这是否是O(N)时间。

2 个答案:

答案 0 :(得分:0)

This solution would require three O(N) traversings of the list, so it will still be O(N). The problem with it is that it creates a new list, and the requirements seem to imply inplace sorting.

An inplace approach could be to go over the list, and move any items starting with A to the beginning and any items starting with C to the end. E.g.:

for item in list:
    if item.data[0] == 'A'
        item.remove()
        list.prepend(item.data)
    elif item.data[0] == 'C'
        item.remove()
        list.append(item.data)

Notes:

  1. item in this pseudocode snippet is the node object of the list - item.data is the data contained in it.
  2. This solution assumes your list has prepend and append methods. If it doesn't, though, it shouldn't be too difficult to implement them.

答案 1 :(得分:0)

You're close. Start with 3 empty lists, and distribute strings into those in a single pass through the original list. Keep a pointer to the last element of the 'A and 'B' lists (the first elements inserted) so that catenating the lists together doesn't require retraversal to find their ends.