给定一个带有头结点 head
的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
试题链接:https://leetcode-cn.com/problems/middle-of-the-linked-list/
public static ListNode middleNode(ListNode head) {
if(head == null) return null;
//定义辅助指针
ListNode pCurrent = head;
//获取链表的长度
int count = 0;
while(pCurrent != null) {
count++;
pCurrent = pCurrent.next;
}
pCurrent = head;
//如果是奇数
for(int i = 2;i <= count/2 + 1;i++ ) {
pCurrent = pCurrent.next;
}
return pCurrent;
}
测试结果:
public static ListNode middleNode(ListNode head) {
if(head == null) return null;
//定义快慢指针
ListNode p1 = head; //快指针
ListNode p2 = head; //慢指针
//1-2-3-4-5
//p1走两步,p2走一步
while(p2 != null && p2.next != null) {
p1 = p1.next;
p2 = p2.next.next;
}
return p1;
}
测试结果:
struct ListNode* middleNode(struct ListNode* head){
if(head == NULL) return NULL;
//定义辅助指针
struct ListNode* pCurrent = head;
//获取链表的长度
int count = 0;
while(pCurrent != NULL) {
count++;
pCurrent = pCurrent->next;
}
pCurrent = head;
//如果是奇数
for(int i = 2;i <= count/2 + 1;i++ ) {
pCurrent = pCurrent->next;
}
return pCurrent;
}
测试结果:
struct ListNode* middleNode(struct ListNode* head){
if(head == NULL) return NULL;
//定义快慢指针
struct ListNode* p1 = head; //快指针
struct ListNode* p2 = head; //慢指针
//1-2-3-4-5
//p1走两步,p2走一步
while(p2 != NULL && p2->next != NULL) {
p1 = p1->next;
p2 = p2->next->next;
}
return p1;
}
测试结果:
原文:https://www.cnblogs.com/xgp123/p/12395946.html