Ejemplo n.º 1
0
def reorder_list(orig_list):
    dummy = ListNode(0)
    dummy.next = orig_list.head
    p = q = dummy
    # find the break point
    while p and p.next:
        p = p.next.next
        q = q.next

    # break the list
    r = q.next
    q.next = None
    second_half = LinkList()
    second_half.head = r

    # reverse the second half
    second_half.reverse_list()

    # merge
    p = orig_list.head
    r = second_half.head
    while r:
        p_next = p.next
        r_next = r.next
        r.next = p.next
        p.next = r
        r = r_next
        p = p_next
    del second_half
    return orig_list
Ejemplo n.º 2
0
def add_lists_reverse(list1, list2):
    ''' add two lists in reverse order
    '''

    p = list1.head
    q = list2.head

    carry = 0
    sum_list = LinkList()

    while p and q:
        curr_sum_digit = (p.data + q.data + carry) % 10
        carry = (p.data + q.data + carry) / 10
        sum_list.append_node(ListNode(curr_sum_digit))
        p = p.next
        q = q.next
    while q:
        curr_sum_digit = (q.data + carry) % 10
        carry = (q.data + carry) / 10
        sum_list.append_node(ListNode(curr_sum_digit))
        q = q.next
    while p:
        curr_sum_digit = (p.data + carry) % 10
        carry = (p.data + carry) / 10
        sum_list.append_node(ListNode(curr_sum_digit))
        p = p.next
    if carry == 1:
        sum_list.append_node(ListNode(1))

    return sum_list
Ejemplo n.º 3
0
def reorder_list(orig_list):
    dummy = ListNode(0)
    dummy.next = orig_list.head
    p = q = dummy
    # find the break point
    while p and p.next:
        p = p.next.next
        q = q.next
    
    # break the list
    r = q.next
    q.next = None
    second_half = LinkList()
    second_half.head = r
    
    # reverse the second half
    second_half.reverse_list()
    
    # merge
    p = orig_list.head
    r = second_half.head
    while r:
        p_next = p.next
        r_next = r.next
        r.next = p.next
        p.next = r
        r = r_next
        p = p_next
    del second_half
    return orig_list
Ejemplo n.º 4
0
def add_lists_reverse(list1, list2):
    """ add two lists in reverse order
    """

    p = list1.head
    q = list2.head

    carry = 0
    sum_list = LinkList()

    while p and q:
        curr_sum_digit = (p.data + q.data + carry) % 10
        carry = (p.data + q.data + carry) / 10
        sum_list.append_node(ListNode(curr_sum_digit))
        p = p.next
        q = q.next
    while q:
        curr_sum_digit = (q.data + carry) % 10
        carry = (q.data + carry) / 10
        sum_list.append_node(ListNode(curr_sum_digit))
        q = q.next
    while p:
        curr_sum_digit = (p.data + carry) % 10
        carry = (p.data + carry) / 10
        sum_list.append_node(ListNode(curr_sum_digit))
        p = p.next
    if carry == 1:
        sum_list.append_node(ListNode(1))

    return sum_list
Ejemplo n.º 5
0
def re_kth_to_end(llist_head, kth):
    if llist_head is None:
        return None

    i = 1
    it = llist_head
    while it is not None:
        if i != kth:
            i += 1
            it = it.next
        else:
            # return new linked list
            LinkList.print_from_head_node(it)
            return it

    # kth is larger than the size of the total nodes
    # return null
    return None
Ejemplo n.º 6
0
def add_two_lists(list1, list2):
    sum_list = LinkList()
    p = list1.head
    q = list2.head
    carry = 0
    while p or q:
        first = p.data if p else 0
        second = q.data if q else 0
        sum = first + second + carry
        carry = sum / 10
        sum = sum % 10
        sum_list.append_node(ListNode(sum))
        if p:
            p = p.next
        if q:
            q = q.next
    if carry:
        sum_list.append_node(ListNode(carry))
    return sum_list
Ejemplo n.º 7
0
def swap(n1,n2):
	temp = LL.ListNode(0)
	temp.data = n1.data
	temp.next = n1.next

	n1.data = n2.data
	n2.data = temp.data

	n1.next = n2.next
	n2.next = temp.next
Ejemplo n.º 8
0
def merge_lists(lists):
    ''' merge len(lists) sorted linked lists, and return the result linked list
    '''
    for each_list in lists:        
        each_list.append_node(ListNode(sys.maxint))
    min_heap = Heap()
    result_list = LinkList()
    curr_nodes = [each_list.head for each_list in lists]
    curr_datas = [node.data for node in curr_nodes]
    # build the heap according to curr_datas
    min_heap.build_heap('min', curr_datas)
    # min_heap.heap[0] == maxint means all the lists go to end, only then, stop the while loop
    while min_heap.heap[0] != sys.maxint:
        # extract min node
        curr_min = min_heap.extract_node()
        # append to result
        result_list.append_node(ListNode(curr_min))
        min_index = curr_datas.index(curr_min)
        curr_nodes[min_index] = curr_nodes[min_index].next
        curr_datas[min_index] = curr_nodes[min_index].data
        # insert the extracted node's next's data, and re-heapify
        min_heap.add_node(curr_datas[min_index])
    return result_list
Ejemplo n.º 9
0
def merge_two_lists_1(listA, listB):
    p = listA.head
    q = listB.head
    if not p:
        return listB
    if not q:
        return listA
    result_list = LinkList()
    #tail = ListNode(0)
    #tail.next = result_list.head
    while p and q:
        if p.data < q.data:
            result_list.append_node(ListNode(p.data))
            p = p.next
        else:
            result_list.append_node(ListNode(q.data))
            q = q.next

    if p:
        result_list.append_node(p)
    if q:
        result_list.append_node(q)
    return result_list
def merge_two_lists_1(listA, listB):
    p = listA.head
    q = listB.head
    if not p:
        return listB
    if not q:
        return listA 
    result_list = LinkList()
    #tail = ListNode(0)
    #tail.next = result_list.head
    while p and q:
        if p.data < q.data:
            result_list.append_node(ListNode(p.data))
            p = p.next
        else:
            result_list.append_node(ListNode(q.data))
            q = q.next
        
    if p:
        result_list.append_node(p)
    if q:
        result_list.append_node(q)
    return result_list
Ejemplo n.º 11
0
def create():
   #创建41人节点
    dic = {}
    for i in range(1,42):
        linknode_val = {"num":i, "note":False}
        dic["P{}".format(i)] = LinkList.LinkList.LinkNode(linknode_val, None)
        if i == 16:
            dic["P{}".format(i)].val["note"] = True
        if i == 31:
            dic["P{}".format(i)].val["note"] = True

    #将链表连接,变成循环链表
    link = LinkList.LinkList()
    link.link_list()
    link.head = dic["P1"]
    cur = link.head
    for i in range(2,42):
        cur.next = dic["P{}".format(i)]
        print(cur.next, i)
        cur = cur.next
    dic["P41"].next = link.head
    print(dic["P41"].next)

   #进行问题模拟
    n = 41
    count = 1
    cur = link.head
    while n > 2:
        count += 1

        if count % 3 == 0:
           cur.next = cur.next.next
           count = 1
           n -=1

        cur = cur.next
    if n == 2:
        print(cur.val["note"], cur.next.val["note"])
Ejemplo n.º 12
0
class UnorderList:

    list1 = LinkList()
    f = open('demo.txt', 'rw+')
    split_Word = f.read().split(" ")
    index = 0
    length = len(split_Word)
    while index < length:
        list1.insertdata(str(split_Word[index]))
        index += 1
    list1.printList()
    word = raw_input("enter the word which you want to search\n")
    result = list1.search(word)
    if result:
        list1.deleteword(word)
        list1.printList()
    else:
        list1.insertdata(word)
        list1.printList()

    list1.updateList()

    # print f.read()
    f.close()
Ejemplo n.º 13
0
def add_two_lists(list1, list2):
    sum_list = LinkList()
    p = list1.head
    q = list2.head
    carry = 0
    while p or q:
        first = p.data if p else 0
        second = q.data if q else 0
        sum = first + second + carry
        carry = sum / 10
        sum = sum % 10
        sum_list.append_node(ListNode(sum))
        if p:
            p = p.next
        if q:
            q = q.next
    if carry:
        sum_list.append_node(ListNode(carry))
    return sum_list
Ejemplo n.º 14
0
def returnKthToLast(head, k):
    fast = head
    # for _ in range(1, k): #range(10) is 0~9 range(1,3) = [1,2]
    #   if fast:
    #       fast = fast.next
    #   else:
    #       return None

    # let fast pointer go k step in advance
    i = 1
    while i <= k:
        if fast:
            fast = fast.next
            i += 1
        else:
            return None

    slow = head
    # fast is now k nodes ahead of slow

    while fast:
        fast = fast.next
        slow = slow.next

    return slow


llist = LinkedList()
llist.initial_with_string("abcdefg")  # g-f-e-d-c-b-a
LinkList.print_from_head_node(returnKthToLast(llist.head, 3))
Ejemplo n.º 15
0

# recursive
def merge_two_lists_2(list_1, list_2):
    result = LinkList()
    result.head = merge_two_lists_helper(list_1.head, list_2.head)
    return result


def merge_two_lists_helper(head_1, head_2):
    if not head_1:
        return head_2
    if not head_2:
        return head_1
    if head_1.data < head_2.data:
        head_1.next = merge_two_lists_helper(head_1.next, head_2)
        return head_1
    else:
        head_2.next = merge_two_lists_helper(head_1, head_2.next)
        return head_2


if __name__ == '__main__':
    test_cases = [([1, 3, 5, 6], [2, 4]), ([1, 3, 5], []),
                  ([1, 2, 3, 4], [5, 6, 7, 8]), ([2], [1])]
    for each_test_case in test_cases:
        listA_list, listB_list = each_test_case
        listA = LinkList(listA_list)
        listB = LinkList(listB_list)
        merge_two_lists_1(listA, listB).print_list()
        merge_two_lists_2(listA, listB).print_list()
Ejemplo n.º 16
0
def merge_two_lists_2(list_1, list_2):
    result = LinkList()
    result.head = merge_two_lists_helper(list_1.head, list_2.head)
    return result
class StockAccountImplementation:
    list_obj = LinkedListStack()
    customerFile = "customer.json"
    companyFile = "company.json"
    transactionFile = "transaction.json"
    linklist_obj = LinkList()
    transaction_obj = Transaction()

    # /*
    #  * Function to read json data from file
    #  * @param filename
    #  */
    def read_json(self, filename):
        jsonDataObj = json.load(open(filename, "r"))
        return jsonDataObj

    # /*
    #  * Function to save data into json formate in file
    #  * @param data
    #  * @param filename
    #  */
    def save(self, data, filename):
        with open(filename, 'w') as temp:
            json.dump(data, temp)
        print("Person Detail Added Successfully!")

    # /*
    #  * Function to add customers
    #  */
    def add_customer(self):
        print "Customer Information"
        name = raw_input("enter customer name : ")
        amount = raw_input("enter a amount : ")
        no_Of_Share = raw_input("Enter the Number Of Share : ")
        customer_obj = Customer(name, amount, no_Of_Share)
        customer_obj.set_customer_name(name)
        customer_obj.set_amount(amount)
        customer_obj.set_noOfShare(no_Of_Share)
        customer = self.read_json(self.customerFile)
        customer["customers"].append({
            "cname":
            customer_obj.get_customer_name(),
            "noOfShare":
            customer_obj.get_noOfShare(),
            "amount_per_share":
            customer_obj.get_amount()
        })
        self.list_obj.push(customer)
        self.save(customer, self.customerFile)

    # /*
    #  * Function to display customers
    #  */
    def display_customer(self):
        customer_data = self.read_json(self.customerFile)
        print "\t\tName\tNoOfShare\tAmount\t"

        for data in customer_data["customers"]:
            print "\n\t\t",data["cname"],"\t\t", data["noOfShare"],"\t\t",\
                data["amount_per_share"]
        print "\n"

    # /*
    #  * Function to display customers
    #  */
    def add_company(self):
        print "Customer Information"
        company_name = raw_input("enter company name : ")
        company_symbol = raw_input("enter a company Symbol : ")
        share_price = raw_input("Enter the Price Of Share : ")
        total_share = raw_input("Enter the total Number Of Share : ")
        company_obj = Company(company_name, company_symbol, share_price,
                              total_share)
        company_obj.set_company_name(company_name)
        company_obj.set_company_symbol(company_symbol)
        company_obj.set_share_price(share_price)
        company_obj.set_total_share(total_share)
        company = self.read_json("company.json")
        company["company"].append({
            "company_name":
            company_obj.get_company_name(),
            "company_symbol":
            company_obj.get_company_symbol(),
            "share_Price":
            company_obj.get_share_price(),
            "total_share":
            company_obj.get_total_share()
        })
        self.list_obj.push(company)
        self.save(company, self.companyFile)

    # /*
    #  * Function to display customers
    #  */
    def display_company(self):
        company_data = self.read_json(self.companyFile)
        print "\t\tName\tSymbol\tShare Price\t"
        for data in company_data["company"]:
            print "\n\t\t", data["company_name"],"\t\t", data['company_symbol'], "\t\t", \
            data["share_Price"]
        print "\n"

    # /*
    #  * Function to search a companies/customers data
    #  * @param search_data
    #  * @param file
    #  * @param temp
    #  * @return
    #  */
    def search(self, search_data, file, temp):
        try:
            file_data = self.read_json(file)
            count = 0
            if temp == 'company':
                for data in file_data[temp]:
                    if (data["company_symbol"] == search_data
                            or data["company_name"] == search_data):
                        count += 1
                        print "company data found"

                        companyName = data["company_name"]
                        company_symbol = data["company_symbol"]
                        total_share = data["total_share"]
                        share_Price = data["share_Price"]

                        new_obj = {
                            "company_name": companyName,
                            "company_symbol": company_symbol,
                            "total_share": total_share,
                            "share_Price": share_Price
                        }
            else:
                for data in file_data[temp]:
                    if (data["cname"] == search_data):
                        count += 1
                        print "customers data found"

                        customername = data["cname"]
                        no_of_share = data["noOfShare"]
                        amount_per_share = data["amount_per_share"]

                        new_obj = {
                            "cname": customername,
                            "noOfShare": no_of_share,
                            "amount_per_share": amount_per_share
                        }
            if count == 0:
                return None
            else:
                return new_obj

        except SyntaxError:
            print "error in name"

    # /*
    #  * Function to do transaction
    #  */
    def tansaction(self):
        print "enter 1.)Buy Share"
        print "enter 2.)Sell Share"

        choice = input("Enter your choice : ")

        if choice == 1:
            self.buy_shares()
        elif choice == 2:
            self.sell_share()

    # /*
    #  * Function to buy shares
    #  */
    def buy_shares(self):
        symbol = raw_input("Enter Company Symbol to Buy Shares : ")
        company = self.search(symbol, self.companyFile, "company")
        if company != None:
            name = raw_input(
                "Enter Customer Name from whom Company wants to buy shares : ")
            customer = self.search(name, self.customerFile, "customers")
            print customer
            if customer != None:
                amount = raw_input("Enter amount to buy shares : ")
                if customer["amount_per_share"] > 0:
                    print customer["amount_per_share"]
                    noofShares = raw_input("Enter number of shares to buy : ")
                    if company["total_share"] < 0:
                        self.buy(amount, noofShares, customer, company, name)
                    else:
                        print "company shares no left"
                        exit(0)
                else:
                    print "customer has no money"
                    exit(0)
            else:
                print "Customer Not Found"
        else:
            print "Company outer Not Found"

    # /*
    #  * Function to buy stocks
    #  * @param amount
    #  * @param noofShares
    #  * @param customer
    #  * @param company
    #  * @param name
    #  */
    def buy(self, amount, noofShares, customer, company, name):
        print company
        if amount >= company["share_Price"]:
            if noofShares <= customer["noOfShare"]:
                sharePrice = company["share_Price"]
                shares = int(amount) / int(sharePrice)

                new_customer_amount = int(
                    customer["amount_per_share"]) - int(amount)
                new_no_of_share = int(customer["noOfShare"]) + int(noofShares)
                print "Customer.shares : ", customer["noOfShare"]

                new_company_share = int(
                    company["total_share"]) - int(noofShares)
                self.transaction_obj.set_customer_name(customer["cname"])
                self.transaction_obj.set_company_symbol(
                    company["company_symbol"])
                self.transaction_obj.set_buy_sell("Buy")
                self.transaction_obj.set_total_share(str(shares))
                self.transaction_obj.set_total_price(amount)

                now = datetime.datetime.now()
                today = now.strftime("%Y-%m-%d %H:%M")
                self.transaction_obj.set_time(today)
                transaction = self.read_json(self.transactionFile)
                transaction["transaction"].append({
                    "customer_name":
                    self.transaction_obj.get_customer_name(),
                    "company_symbol":
                    self.transaction_obj.get_company_symbol(),
                    "buy_sell":
                    self.transaction_obj.get_buy_sell(),
                    "total_share":
                    self.transaction_obj.get_total_share(),
                    "total_Price":
                    self.transaction_obj.get_total_price(),
                    "time":
                    self.transaction_obj.get_time()
                })

                self.save(transaction, self.transactionFile)
                self.linklist_obj.insertdata(transaction)

                customer_data = self.read_json(self.customerFile)
                for item in customer_data["customers"]:

                    if item["cname"] == name:
                        print "if"
                        print item["amount_per_share"]
                        item["amount_per_share"] = str(new_customer_amount)
                        item["noOfShare"] = str(new_no_of_share)

                        self.save(customer_data, self.customerFile)
                company_data = self.read_json(self.companyFile)

                for item in company_data["company"]:

                    if item["company_name"] == company["company_name"]:
                        item["total_share"] = str(new_company_share)

                        self.save(company_data, self.companyFile)

    # /*
    #  * Function to sell stocks
    #  * @param amount
    #  * @param noofShares
    #  * @param customer
    #  * @param company
    #  * @param name
    #  */
    def sell(self, amount, noofShares, customer, company, name):
        print customer["noOfShare"]
        print noofShares

        if noofShares <= customer["noOfShare"]:
            print "if"
            if amount <= company["share_Price"]:
                sharePrice = customer["amount_per_share"]
                print "if1"
                shares = int(amount) / int(sharePrice)
                print "Shares : ", shares
                print company["share_Price"]

                new_customer_amount = int(
                    customer["amount_per_share"]) + int(amount)
                new_no_of_share = int(customer["noOfShare"]) - int(noofShares)
                print "Customer.shares : ", customer["noOfShare"]

                new_company_share = int(
                    company["total_share"]) + int(noofShares)

                self.transaction_obj.set_customer_name(customer["cname"])
                self.transaction_obj.set_company_symbol(
                    company["company_symbol"])
                self.transaction_obj.set_buy_sell("Sell")
                self.transaction_obj.set_total_share(str(shares))
                self.transaction_obj.set_total_price(amount)

                now = datetime.datetime.now()
                today = now.strftime("%Y-%m-%d %H:%M")
                self.transaction_obj.set_time(today)
                transaction = self.read_json(self.transactionFile)
                transaction["transaction"].append({
                    "customer_name":
                    self.transaction_obj.get_customer_name(),
                    "company_symbol":
                    self.transaction_obj.get_company_symbol(),
                    "buy_sell":
                    self.transaction_obj.get_buy_sell(),
                    "total_share":
                    self.transaction_obj.get_total_share(),
                    "total_Price":
                    self.transaction_obj.get_total_price(),
                    "time":
                    self.transaction_obj.get_time()
                })
                self.save(transaction, self.transactionFile)
                customer_data = self.read_json(self.customerFile)
                for item in customer_data["customers"]:
                    if item["cname"] == name:
                        item["amount_per_share"] = str(new_customer_amount)
                        item["noOfShare"] = str(new_no_of_share)

                        self.save(customer_data, self.customerFile)
                        print("Person Detail Added Successfully!")

                company_data = self.read_json(self.companyFile)
                for item in company_data["company"]:
                    if item["company_name"] == company["company_name"]:
                        item["total_share"] = str(new_company_share)
                        self.save(company_data, self.companyFile)
                        print("Person Detail Added Successfully!")

    # /*
    #  * Function to sell stock
    #  */
    def sell_share(self):
        customer_name = raw_input("Enter Customer Name : ")
        customer = self.search(customer_name, self.customerFile, "customers")

        if customer != None:
            company_name = raw_input("Enter Company name to buy share : ")
            company = self.search(company_name, self.companyFile, "company")

            if company != None:
                amount = raw_input("Enter amount to buy shares : ")
                noofShares = raw_input("Enter number of shares to buy : ")
                self.sell(amount, noofShares, customer, company, customer_name)
            else:
                print "Customer Not Found"
        else:
            print "Company Not Found"

    # /*
    #  * Function to display all transaction
    #  */
    def display_transaction(self):
        transaction_display = self.read_json(self.transactionFile)
        for data in transaction_display["transaction"]:
            print "customer_name : ", data["customer_name"]
            print "buy or sell : ", data["buy_sell"]
            print "total_share : ", data["total_share"]
            print "total_Price : ", data["total_Price"]
            print "time : ", data["time"], "\n"
Ejemplo n.º 18
0
def add_two_lists(list1, list2):
    sum_list = LinkList()
    p = list1.head
    q = list2.head
    carry = 0
    while p or q:
        first = p.data if p else 0
        second = q.data if q else 0
        sum = first + second + carry
        carry = sum / 10
        sum = sum % 10
        sum_list.append_node(ListNode(sum))
        if p:
            p = p.next
        if q:
            q = q.next
    if carry:
        sum_list.append_node(ListNode(carry))
    return sum_list


if __name__ == '__main__':
    test_cases = [([7, 1, 6], [1, 5, 9, 2]), ([1], [9, 9, 9]),
                  ([1, 2, 3], [4, 5, 6]), ([8, 5, 6], [3, 7, 5])]
    for each_test_case in test_cases:
        list1 = LinkList(each_test_case[0])
        list2 = LinkList(each_test_case[1])
        print each_test_case
        add_lists_reverse(list1, list2).print_list()
        add_two_lists(list1, list2).print_list()
Ejemplo n.º 19
0
 def __init__(self):
     self.linklist = LinkList.LinkList()
Ejemplo n.º 20
0
    def match(self, text):
        #初始化父节点的索引
        parent_index = -1
        #初始化等级
        level = 0
        #外层循环遍历字符串每个字符
        for i in range(len(text)):
            #如果是左括号,入栈
            for j in range(len(self.allLeft)):
                if text[i] == self.allLeft[j]:

                    #创建括号对象
                    bt = Bracket()
                    bt.level = level
                    level += 1
                    #设置相关属性
                    bt.setLeft(text[i], i)
                    bt.setType(text[i] + self.allRight[j])

                    #与表头比对level来确认父子级关系
                    if not self.LinkList.head:
                        #如果表头为空,不做操作
                        #print("空")
                        pass
                    elif bt.level == self.LinkList.head.value.level:
                        #同级关系保持父节点一致
                        bt.parent = self.brackets[-1].parent
                        #父节点不为空则将当前节点添加为子节点

                        if self.brackets[-1].parent != None:

                            self.brackets[-1].parent.children.append(bt)
                    else:
                        #print("父节点")
                        #父子关系则当前节点置为子节点
                        bt.parent = self.LinkList.head.value
                        #父节点不为空则将当前节点添加为子节点
                        if self.LinkList.head.value != None:

                            self.LinkList.head.value.children.append(bt)

                    #将该元素入栈
                    self.LinkList.append(LinkList.LElement(bt))

            #如果是右括号,出栈
            for j in range(len(self.allRight)):
                if text[i] == self.allRight[j]:
                    level -= 1
                    #如果为空,说明非法
                    if not self.LinkList.head:
                        raise Exception("括号匹配器:语义非法!")
                    #如果该右括号匹配
                    if self.LinkList.head.value._type[1] == text[i]:
                        #获取表头
                        bt = self.LinkList.head.value
                        #出栈
                        self.LinkList.delete()
                        level -= 1
                        #设置相关属性
                        bt.setRight(text[i], i)
                        bt.setTextFromTotal(text)

                        self.brackets.append(bt)
Ejemplo n.º 21
0
''' 3->1->2->5->2->1->3   compare 3f to 3b(return value) if equal, return (True, None)   first_node=3f, length=7
       1->2->5->2->1->3   compare 1f(3f.next) to 1b(return value) if equal, return (True, 3b(1f.next))     first_node=1f(3f.next), length=5
          2->5->2->1->3   compare 2f(1f.next) to 2b(return value) if equal, return (True, 1b(2b.next))     first_node=2f(1f.next), length=3
             5->2->1->3   first_node=5 length==1 return (True, 2b)


'''


def isPalindrome_2_helper(first_node, length):
    if length == 0:
        return (True, first_node)
    if length == 1:
        return (True, first_node.next)
    front_node = first_node
    return_tuple = isPalindrome_2_helper(first_node.next, length - 2)
    return_result = return_tuple[0]
    back_node = return_tuple[1]
    if return_result == False:
        return (False, back_node.next)
    if front_node.data != back_node.data:
        return (False, back_node.next)
    else:
        return (True, back_node.next)


if __name__ == '__main__':
    a = LinkList([3, 1, 2, 5, 2, 1, 3])
    print isPalindrome_1(a)
    print isPalindrome_2(a)
def merge_two_lists_2(list_1, list_2):
    result = LinkList()
    result.head = merge_two_lists_helper(list_1.head, list_2.head)
    return result
Ejemplo n.º 23
0
from LinkList import *


def reverse_linked_list(orig_list, m, n):
    assert (1 <= m <= n <= len(orig_list))
    dummy = ListNode(0)
    dummy.next = orig_list.head
    p = dummy
    count = n - m
    while m - 1 > 0:
        p = p.next
        m -= 1
    q = p.next
    while count > 0:
        r = q.next
        q.next = r.next
        r.next = p.next
        p.next = r
        count -= 1
    orig_list.head = dummy.next
    return orig_list


if __name__ == '__main__':
    test_cases = [([1, 2, 3, 4, 5, 6], 6, 6), ([1, 2, 3], 1, 3)]
    for each_test_case in test_cases:
        orig_list_data, m, n = each_test_case
        orig_linkedlist = LinkList(orig_list_data)
        print each_test_case
        reverse_linked_list(orig_linkedlist, m, n).print_list()
        lenA += 1
    while tailB.next:
        tailB = tailB.next
        lenB += 1
    if tailA is not tailB:
        return None
    if lenA < lenB:
        diff = lenB-lenA
        while diff > 0:
            headB = headB.next
            diff -= 1
    elif lenB < lenA:
        diff = lenA-lenB
        while diff > 0:
            headA = headA.next
            diff -= 1
    while headA:
        if headA == headB:
            return headA
        headA = headA.next
        headB = headB.next
        
        
if __name__=='__main__':
    la = LinkList([1,3,5,6,7,8,9,10])
    lb = LinkList([2,4])
    tb = lb.get_tail_node()
    tb.next = la.head.next.next.next
    lb.print_list()
    
    print get_intersection_node(la, lb)
Ejemplo n.º 25
0
        while l1 or l2:
            a, b = 0, 0
            if l1:
                a = l1.val
                l1 = l1.next
            if l2:
                b = l2.val
                l2 = l2.next
            temp = a + b
            if temp + full < 10:
                sum_.next = ListNode(temp + full)
                full = 0
            else:
                sum_.next = ListNode(temp + full - 10)
                full = 1
            sum_ = sum_.next

        if not full:
            return sum_node
        else:
            sum_.next = ListNode(1)
            return sum_node


if __name__ == '__main__':
    l1, l2 = LinkList._construct_link([9]), LinkList._construct_link([9])
    out = Solution().addTwoNumbers(l1, l2)
    LinkList._visualize_link(out)


Ejemplo n.º 26
0
    ''' merge len(lists) sorted linked lists, and return the result linked list
    '''
    for each_list in lists:        
        each_list.append_node(ListNode(sys.maxint))
    min_heap = Heap()
    result_list = LinkList()
    curr_nodes = [each_list.head for each_list in lists]
    curr_datas = [node.data for node in curr_nodes]
    # build the heap according to curr_datas
    min_heap.build_heap('min', curr_datas)
    # min_heap.heap[0] == maxint means all the lists go to end, only then, stop the while loop
    while min_heap.heap[0] != sys.maxint:
        # extract min node
        curr_min = min_heap.extract_node()
        # append to result
        result_list.append_node(ListNode(curr_min))
        min_index = curr_datas.index(curr_min)
        curr_nodes[min_index] = curr_nodes[min_index].next
        curr_datas[min_index] = curr_nodes[min_index].data
        # insert the extracted node's next's data, and re-heapify
        min_heap.add_node(curr_datas[min_index])
    return result_list

if __name__=='__main__':
    lists=[[2,5,8], [1,4,10], [3,6,7]]
    linklists=[]
    for each_list in lists:
        linklists.append(LinkList(each_list))
    for each_list in linklists:
        each_list.print_list()
    merge_lists(linklists).print_list()
Ejemplo n.º 27
0
        fast = fast.next.next
    l1 = head
    l2 = slow.next
    slow.next = None
    nh_1 = merge_sort_list_helper(l1)
    nh_2 = merge_sort_list_helper(l2)
    return merge(nh_1, nh_2)


def merge(l1, l2):
    if not l1:
        return l2
    if not l2:
        return l1
    if l1.data <= l2.data:
        l1.next = merge(l1.next, l2)
        return l1
    else:
        l2.next = merge(l1, l2.next)
        return l2


if __name__ == '__main__':
    test_cases = [[3, 7, 4, 8, 6, 5], [10, 7, 4, 11, 5, 2, 6, 19, 1], [1],
                  [5, 4], [6, 5, 4, 3, 2, 2], [10, 4, 7, 11, 5, 11, 2, 4]]
    for each_test_case in test_cases:
        orig_list = LinkList(each_test_case)
        insertion_sort_list(orig_list).print_list()
        orig_list = LinkList(each_test_case)
        merge_sort_list(orig_list).print_list()
Ejemplo n.º 28
0
curr_node = None


def list2bst(my_list):
    global curr_node
    curr_node = my_list.head.next
    root = list2bst_helper(0, len(my_list) - 1)
    return BinaryTree(root)


def list2bst_helper(start, end):
    global curr_node
    if start > end:
        return None
    mid = start + (end - start) / 2
    left_child = list2bst_helper(start, mid - 1)
    parent = TreeNode(curr_node.data)
    curr_node = curr_node.next
    parent.left = left_child
    parent.right = list2bst_helper(mid + 1, end)
    return parent


if __name__ == '__main__':
    test_cases = [[1, 2, 3, 4, 5, 6]]
    for each_test_case in test_cases:
        my_list = LinkList(each_test_case)
        bst = list2bst(my_list)
        bst.pre_order_print(bst.root)
        print
        bst.in_order_print(bst.root)
Ejemplo n.º 29
0
def merge_sort_list(orig_list):
    nh = merge_sort_list_helper(orig_list.head)
    result_list = LinkList()
    result_list.head = nh
    return result_list
Ejemplo n.º 30
0
from LinkList import *

l1 = LinkList()
l2 = LinkList()

l1.init_list([1, 5, 7, 8, 10, 19])
l2.init_list([0, 3, 4, 9])

l1.show()
l2.show()


def merge(list_target01, list_target02):
    # 将list_target02合并到list_target01中
    p = list_target01.head
    q = list_target02.head.next
    while p.next is not None:
        if p.next.value < q.value:
            p = p.next
        else:
            temp = p.next
            p.next = q
            p = p.next
            q = temp
    p.next = q


merge(l1, l2)
print("===============================")
l1.show()
Ejemplo n.º 31
0
def merge_sort_list(orig_list):
    nh = merge_sort_list_helper(orig_list.head)
    result_list = LinkList()
    result_list.head = nh
    return result_list
Ejemplo n.º 32
0
#Solution:变量tmp用于储存当前data的node,如果下一个节点的
#data和cur.data相同,那么tmp内容不变,继续遍历链表;
#若cur.data != cur.next.data,说明内容发生了变换,
#则要用tmp.next连接cur.next,并用cur.next更新tmp;
#最后一个tmp注意和后面的节点断开,即加上tmp.next = 0
def deleteDuplicates(head):
    #newhead = head
    if head == 0 or head.next == 0:
        return head
    cur = head
    tmp = head
    while cur.next:
        if cur.data != cur.next.data:
            tmp.next = cur.next
            tmp = cur.next
        cur = cur.next

    tmp.next = 0

    return head


l = LL.LinkList()
h = l.initlist([1, 1])

h_remove = deleteDuplicates(h)

while h_remove:
    print h_remove.data
    h_remove = h_remove.next
        p = p.next
        # case 1: insert between previous and current
        if prev.data <= val <= p.data:
            break
        # case 2: insert at end or beginning
        if prev.data > p.data and (val > prev.data or val < p.data):
            break
        # case 3: when duplicates in list, traverse back to start point
        if p == node:
            break
    new_node = ListNode(val)
    prev.next = new_node
    new_node.next = p
    #return orig_list


if __name__ == '__main__':
    orig_list = LinkList([1, 3, 3, 4])
    p = q = orig_list.head
    orig_list.make_loop(0)
    node = q.next.next  # node = second 3
    print orig_list.loop_length()
    for val in [2, 3, 5]:
        insert_node_cyclic(orig_list, node, val)
        p = q = orig_list.head
        print p.data,
        p = p.next
        while p != q:
            print p.data,
            p = p.next
        print
        lenA += 1
    while tailB.next:
        tailB = tailB.next
        lenB += 1
    if tailA is not tailB:
        return None
    if lenA < lenB:
        diff = lenB - lenA
        while diff > 0:
            headB = headB.next
            diff -= 1
    elif lenB < lenA:
        diff = lenA - lenB
        while diff > 0:
            headA = headA.next
            diff -= 1
    while headA:
        if headA == headB:
            return headA
        headA = headA.next
        headB = headB.next


if __name__ == '__main__':
    la = LinkList([1, 3, 5, 6, 7, 8, 9, 10])
    lb = LinkList([2, 4])
    tb = lb.get_tail_node()
    tb.next = la.head.next.next.next
    lb.print_list()

    print get_intersection_node(la, lb)
Ejemplo n.º 35
0
    for j in range(len(A)):
        if A[j] != elem:
            A[i] = A[j]
            i += 1
    return A[:i]


if __name__ == '__main__':
    test_cases = [[1, 1, 2], [1, 1, 2, 3, 3, 3, 4, 4], [1, 2, 3], [1]]
    for each_test_case in test_cases:
        print 'remove dup in array, Q1', each_test_case, remove_dup_in_array_q1(
            each_test_case)
    test_cases = [[1, 1, 2], [1, 1, 2, 3, 3, 3, 4, 4], [1, 2, 3], [1],
                  [1, 2, 2, 2, 3, 3, 4, 4, 4],
                  [1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 6]]
    for each_test_case in test_cases:
        print 'remove dup in array Q2', each_test_case, remove_dup_in_array_q2(
            each_test_case)

    test_cases = [[1, 2, 2, 2, 3, 3], [1], [1, 1, 1, 1], [1, 2, 2, 2, 3, 3, 4]]
    for each_test_case in test_cases:
        print 'remove dup in list Q1', each_test_case
        remove_dup_in_list_q1(LinkList(each_test_case)).print_list()
    test_cases = [[1, 1], [1, 1, 1, 2, 3], [1], [1, 2, 2, 2, 3, 3, 3]]
    for each_test_case in test_cases:
        print 'remove dup in list Q2', each_test_case
        remove_dup_in_list_q2(LinkList(each_test_case)).print_list()

    for each_test_case in test_cases:
        print 'remove element in array', each_test_case, remove_elem(
            each_test_case, 1)
Ejemplo n.º 36
0
 def __init__(self, echo):
     self.LinkList = LinkList.LinkList()  #匹配对应符号时所用到的链表
     self.echo = echo  #所需匹配的一对符号
     self.left_point = None  #左侧在原文中的位置
     self.right_point = None  #右侧在原文中的位置
     self.text = ''  #一对符号之间的内容
Ejemplo n.º 37
0
 def __init__(self):
     self.brackets = []  #储存结果的列表
     self.LinkList = LinkList.LinkList()  #匹配括号时所用到的链表
     self.allLeft = ['[', '{', '(', '<']
     self.allRight = [']', '}', ')', '>']
     self.next = 0  #迭代器使用
        prev = p
        p = p.next
        # case 1: insert between previous and current
        if prev.data <= val <= p.data:
            break
        # case 2: insert at end or beginning
        if prev.data > p.data and (val > prev.data or val < p.data):
            break
        # case 3: when duplicates in list, traverse back to start point
        if p == node:
            break
    new_node = ListNode(val)
    prev.next = new_node
    new_node.next = p
    #return orig_list
    
if __name__=='__main__':
    orig_list = LinkList([1,3,3,4])
    p = q = orig_list.head
    orig_list.make_loop(0)
    node = q.next.next      # node = second 3
    print orig_list.loop_length()
    for val in [2,3,5]:
        insert_node_cyclic(orig_list, node, val)
        p = q = orig_list.head
        print p.data,
        p = p.next
        while p!=q:
            print p.data,
            p = p.next
        print