今天在做一个判断链表有无环的时候用到了结构体,发现了结构体对象调用属性时->和.的区别
先说说这个判断的算法,核心是快慢指针
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if (head==null)
return false;
ListNode slow = head;
ListNode fast = head;
//快慢指针的思想,无欢快指针会到达链表尾,有环的话快慢指针会相遇
while (fast!=null &&fast.next!=null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
}
再说说标题的区别
当访问地址(指针或迭代器)的成员或数据时,用“->”
当访问直接对象的成员或数据时,用“.”
“.”只需要声明一个结构体,格式是结构体类型名+结构体名。然后用结构体名”.”域名就可以引用域了 。
“->”需要声明一个结构体,格式是结构体类型名+结构体名,并且声明一个指针指向该结构体。
struct date {
int month;
int day;
int year;
} myday;
struct date p = &myday;
/* (*p).month = 11; */ p->month = 11;//这两个表达式意思相同