/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverse(struct ListNode* head)
{
struct ListNode* p=head;
struct ListNode *temp=NULL;
struct ListNode *cur2=NULL;
//struct ListNode *cur1=NULL;
int i=0;
if(p==NULL|| p->next==NULL)
return p;
while(p){
temp=p->next;
p->next=cur2;
cur2=p;
p=temp;
}
return cur2;
}
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
head= reverse2(head);
struct ListNode* p=head;
struct ListNode* temp=NULL;
struct ListNode* pre=NULL;
if(head == NULL||n <= 0)
return head;
//delete a note
if(n==1){
temp=head->next;
free(head);//链表的删除是否释放内存,head变量还是其内存?
head=temp;
}
while(p && n > 1)
{
pre=p;
p=p->next;
n--;
}
if(pre!=NULL){
pre->next=p->next;
free(p);
}
head= reverse2( head);
return head;
}
链表的反转和节点删除
最新推荐文章于 2024-07-08 16:25:47 发布