返回链表的中间结点:
代码实现:
链表的定义:
typedef int SListDataType;
typedef struct SListNode {
SListDataType value; // 保存的值
struct SListNode* next; // 保存下一个结点的地址
} SListNode;
typedef struct SHead {
SListNode* first;
}SHead;
返回中间结点的代码:
//返回链表的中间结点
SListNode* zhongSListNode(SHead* s) {
//边界判断
//1.链表不存在
assert(s != NULL);
//2.链表为空
assert(s->first1 + NULL);
//计数器
int count = 0;
//判断是否到中间结点,因为要打印中间结点数据
int count1 = 0;
//先遍历求链表长度
SListNode* cur = s->first;
for (cur = s->first; cur->next != NULL;cur=cur->next) {
count++;
}
//这时候count就是链表长度
count1 = count / 2 + 1;
//开始返回中间结点
while (count != count1) {
cur = cur->next;
count++;
}//退出循环的时候,就找到中间的了
return cur; //返回的是地址
//return cur->value; //返回的是数值,根据你函数类型,如果是int,就返回数值
}