题目 24交换链表节点
/**
- Definition for singly-linked list.
- struct ListNode {
-
int val;
-
struct ListNode *next;
- };
/
struct ListNode swapPairs(struct ListNode* head) {
typedef struct ListNode ListNode;
ListNode* pre=(ListNode*)malloc(sizeof(ListNode));
pre->next=head;
ListNode *q,p;
ListNode w=pre;
p = pre->next;
if(pNULL) return pre->next;
q = p->next;
while (q != NULL&&p!=NULL) {
p->next = q->next;
q->next = p;
w->next = q;
w = p;
p = p->next;
if(pNULL) break;
q = p->next;
}
return pre->next;
}
题目19删除链表的第N个节点
/**
-
Definition for singly-linked list.
-
struct ListNode {
-
int val;
-
struct ListNode *next;
-
};
/
struct ListNode removeNthFromEnd(struct ListNode* head, int n) {
typedef struct ListNode ListNode;
ListNode* pre = (ListNode*)malloc(sizeof(ListNode));
//首先找到这个位置
pre->next = head;
ListNode* p = head;
ListNode* w=pre; //用于记录删除节点的前面一个节点
ListNode* q = head; //用于找到被删节点
for (int i = 0; i<n; i++) { //找到相对位置
p=p->next;}
while § {
w=w->next;
p = p->next;
q = q->next;
}
if (q == head) {
pre->next = q->next;
free(q);
return pre->next;
} else{
w->next=q->next;
free(q);
return pre->next;}
}
题目:07相交链表
/**
-
Definition for singly-linked list.
-
struct ListNode {
-
int val;
-
struct ListNode *next;
-
};
/
struct ListNode getIntersectionNode(struct ListNode headA, struct ListNode headB) {
//首先得出这个链表的长度,是否相等,相等怎么样,不相等如何做
int m=0,n=0;
typedef struct ListNode ListNode;
ListNodepre=(ListNode)malloc(sizeof(ListNode));
ListNodeqre=(ListNode)malloc(sizeof(ListNode));
pre->next=headA;
qre->next=headB;ListNodep=pre;
ListNodeq=qre;while§{
p=p->next;
m++;
}
while(q){
q=q->next;
n++;
}
int val=m-n;
p=pre;
q=qre;
if(val>=0){
for(val;val>0;val–){
p=p->next;
}
}else{
for(val;val<0;val++){
q=q->next;
}
}
while(p&&q){
if(p->valq->val&&qp){
return p;
}
p=p->next;
q=q->next;
}
return NULL;
}
题目 142 环形链表
/**
- Definition for singly-linked list.
- struct ListNode {
-
int val;
-
struct ListNode *next;
- };
/
struct ListNode detectCycle(struct ListNode* head) {
typedef struct ListNode ListNode;
ListNode *fast = head, *slow = head;
while (fast && fast->next) {
// 这里判断两个指针是否相等,所以移位操作放在前面
slow = slow->next;
fast = fast->next->next;
if (slow == fast) { // 相交,开始找环形入口:分别从头部和从交点出发,找到相遇的点就是环形入口
ListNode *f = fast, *h = head;
while (f != h) f = f->next, h = h->next;
return h;
}
}
return NULL;
}