1. 程式人生 > >【LeetCode】No.876 Middle of the Linked List

【LeetCode】No.876 Middle of the Linked List

題目:

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.

即給定一個節點數在1-100之間的連結串列,輸出從中間節點開始的部分;若連結串列的節點數為偶數,則從中間兩個節點的後一個節點開始輸出。

分析:

  使用兩個指標對連結串列的節點進行遍歷,第一個指標的步長為2,第二個指標的步長為1,則當第一個指標走到連結串列尾部時,第二個指標恰好走到連結串列的中間節點。此時以第二個指標指向的節點的起點,輸出連結串列中的所有節點即可。

程式:

#include <iostream>

using namespace std;

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) :val(x), next(NULL) {}
};

ListNode *CreateList();
void AddNode(ListNode *head, int element);
void PrintList(ListNode *head);
ListNode *MiddleNode(ListNode *head);

int main() {
	int element;
	ListNode *middle;
	ListNode *l = CreateList();

	/*新建一個有序連結串列(帶表頭)*/
	cout << "Please input the data of linklist:" << endl;
	while (cin >> element) {
		AddNode(l, element);
		if (cin.get() == '\n') {
			break;
		}
	}

	/*查詢中間節點*/
	cout << "The list starting with the middle node : ";
	middle = MiddleNode(l->next);	//不傳表頭
	PrintList(middle);

	return 0;
}

/*建立空連結串列*/
ListNode *CreateList() {
	ListNode *head = new ListNode(-1);
	return head;
}

/*向表中新增結點*/
void AddNode(ListNode *head, int element) {
	if (!head) {
		cout << "The list is NULL!";
		return;
	}

	ListNode *tmp = head;
	while (tmp->next) {
		tmp = tmp->next;
	}
	ListNode *NewNode = new ListNode(element);
	tmp->next = NewNode;
}

/*列印連結串列*/
void PrintList(ListNode *head) {
	if (!head) {
		cout << "The list is NULL!" << endl;
		return;
	}

	ListNode *p = head;		//middle是無表頭連結串列
	while (p) {
		cout << p->val << " ";
		p = p->next;
	}
	cout << endl;
}

/*查詢中間節點*/
ListNode* MiddleNode(ListNode* head) {
	if (!head) return NULL;

	ListNode *end = head;
	ListNode *middle = new ListNode(-1);
	middle = head;

	while (end->next) {
		middle = middle->next;
		if (end->next->next)
			end = end->next->next;
		else
			break;
	}

	return middle;	//此時的middle是不帶表頭的連結串列
}

執行結果:

avatar