给定一个带有头结点 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; }
测试结果:3d
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; }
测试结果:code
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; }
测试结果:blog