题目:
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是不带表头的链表
}