pezy/LeetCode

Create a LinkedList by initializer_list ?

pezy opened this issue · 2 comments

pezy commented

We always need create some LinkedList in our unit test. Initializer_list is the most easiest way. How to use initializer_list to generate a LinkedList?

For instance:

  • Input: {1,2,3,4,5,6,7,8,9}
  • Output: 1->2->3->4->5->6->7->8->9
pezy commented
ListNode *create_linkedlist(std::initializer_list<int> lst)
{
    auto iter = lst.begin();
    ListNode *head = lst.size() ? new ListNode(*iter++) : NULL;
    for (ListNode *cur=head; iter != lst.end(); cur=cur->next)
        cur->next = new ListNode(*iter++);
    return head;
}

TEST:

for (ListNode *cur=head; cur; cur=cur->next)
    std::cout << cur->val << "->";
std::cout << "\b\b  " << std::endl;

👍