24. 两两交换链表中的节点 ,19.删除链表的倒数第N个节点 ,面试题 02.07. 链表相交 ,142.环形链表II
继续链表题,今天就做完了。
24.两两交换链表中的结点:
好像之前虚拟结点定义错了。
struct ListNode* swapPairs(struct ListNode* head) {
struct ListNode p;
p.next = head;
struct ListNode* pro = &p;
//定义虚拟结点
struct ListNode* pre = head;
while(pre != NULL && pre->next != NULL){
struct ListNode* t = pre->next;
pre->next = t->next;
t->next = pre;
pro->next = t;
pro = pre;
pre = pre->next;
}
return p.next;
}
19.删除链表的倒数第N个节点:
这次是越界的问题。
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode *p = head,*q = head;
int i=0;
for(;i<=n&&p;i++) p=p->next;
if (i<=n) {
head = head->next;
return head; // n 大于链表长度,不进行删除
}
while(p!=NULL){
p=p->next;
q=q->next;
}
q->next = q->next->next;
return head;
}