有哑结点
struct ListNode* removeElements(struct ListNode* head, int val) {
typedef struct ListNode ListNode;
ListNode *shead;
shead = (ListNode*)malloc(sizeof(ListNode));
shead->next = head;
ListNode *cur = shead;
while(cur->next != NULL)
{
if(cur->next->val == val)
{
ListNode *temp = cur->next;
cur->next = cur->next->next;
free(temp);
}
else
{
cur = cur->next;
}
}
head = shead->next;
return head;
}
无哑结点
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode* temp;
while(head && head->val == val)
{
temp = head;
head = head->next;
free(temp);
}
struct ListNode* cur = head;
while(cur && (temp = cur->next))
{
if(temp ->val == val)
{
cur->next = temp->next;
free(temp);
}
else
cur = cur->next;
}
return head;
}
总结:有无哑结点的,就是对头节点如何操作的问题。
typedef struct {
int val;
struct MyLinkedList* next;
} MyLinkedList;
MyLinkedList* myLinkedListCreate() {
MyLinkedList* head = (MyLinkedList *)malloc(sizeof (MyLinkedList));
head->next = NULL;
return head;
}
int myLinkedListGet(MyLinkedList* obj, int index) {
MyLinkedList *cur = obj->next;
for (int i = 0; cur != NULL; i++){
if (i == index){
return cur->val;
}
else{
cur = cur->next;
}
}
return -1;
}
void myLinkedListAddAtHead(MyLinkedList* obj, int val) {
MyLinkedList* nhead = (MyLinkedList*)malloc(sizeof(MyLinkedList));
nhead->val = val;
nhead->next = obj->next;
obj->next = nhead;
}
void myLinkedListAddAtTail(MyLinkedList* obj, int val) {
MyLinkedList *cur = obj;
while(cur->next != NULL){
cur = cur->next;
}
MyLinkedList *ntail = (MyLinkedList *)malloc(sizeof (MyLinkedList));
ntail->val = val;
ntail->next = NULL;
cur->next = ntail;
}
void myLinkedListAddAtIndex(MyLinkedList* obj, int index, int val) {
if (index == 0){
myLinkedListAddAtHead(obj, val);
return;
}
MyLinkedList *cur = obj->next;
for(int count = 1; cur != NULL;count++){
if(count == index)
{
MyLinkedList* new =(MyLinkedList*)malloc(sizeof(MyLinkedList));
new->val = val;
new->next = cur->next;
cur->next = new;
return;
}
else
cur = cur->next;
}
}
void myLinkedListDeleteAtIndex(MyLinkedList* obj, int index) {
if (index == 0){
MyLinkedList *tmp = obj->next;
if (tmp != NULL){
obj->next = tmp->next;
free(tmp);
}
return;
}
MyLinkedList *cur = obj->next;
for (int i = 1 ;cur != NULL && cur->next != NULL; i++){
if (i == index){
MyLinkedList *tmp = cur->next;
if (tmp != NULL) {
cur->next = tmp->next;
free(tmp);
}
return;
}
else{
cur = cur->next;
}
}
}
void myLinkedListFree(MyLinkedList* obj) {
while(obj != NULL)
{
MyLinkedList *tmp = obj;
obj = obj->next;
free(tmp);
}
}
双指针
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* cur = head;
struct ListNode* pre = NULL;
while(cur){
struct ListNode* temp;
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
递归di
struct ListNode*reverse(struct ListNode* cur,struct ListNode* pre ){
if(!cur)
return pre;
struct ListNode* temp = cur->next;
cur->next = pre;
return reverse(temp,cur);
}
struct ListNode* reverseList(struct ListNode* head) {
return reverse(head,NULL);
}