leetcode -- 876、1290

876. Middle of the Linked List

Problem Description

Given a non-empty, singly linked list with head node head, return a middle node of linked list.

If there are two middle nodes, return the second middle node.

Example 1:

Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge’s serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.

Example 2:

Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.

Note:

The number of nodes in the given list will be between 1 and 100

Solution Method

快慢指針

struct ListNode* middleNode(struct ListNode* head)
{
    struct ListNode *p = head, *q = head;
    while (q != NULL && q->next != NULL)
    {
        p = p->next;
        q = q->next->next;
    }
    return p;
}

在這裏插入圖片描述

1290. Convert Binary Number in a Linked List to Integer

Problem Description

Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.

Return the decimal value of the number in the linked list.

Solution Method

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


int getDecimalValue(struct ListNode* head)
{
    struct ListNode * p = head;
    struct ListNode * q = NULL;		// q指向最後一個 1
    int count = 0, integer = 0;
    while (p != NULL)		// 遍歷一次,計算鏈表節點數
    {
        if (p->val == 1)
            q = p;
        count ++;
        p = p->next;
    }
    if (q == NULL)		// 假如鏈表全爲零
        return 0;
    p = head;
    while (p != q->next)		// 計算對應的整數值
    {
        count --;
        if (p->val == 1)		// 等於1的位才計算
            integer += pow(2, count);
        p=p->next;
    }
    return integer;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章