您的位置:首页 > 其它

C实现 LeetCode->Reverse Linked List (双指针大法)(单链表反转)

2015-06-22 15:04 633 查看
Reverse a singly linked list.

/**
 *  Reverse a singly linked list
   反转单链表,请牢记 Reverse()函数
 */


//
// ReverseLinkedList.c
// Algorithms
//
// Created by TTc on 15/6/22.
// Copyright (c) 2015年 TTc. All rights reserved.
//
/**
* Reverse a singly linked list.

反转单链表,请牢记 Reverse()函数
*/
#include "ReverseLinkedList.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "List.h"

/********************************************************************/
// LeetCode 答案
/********************************************************************/
struct ListNode {
int val;
struct ListNode *next;
};

//双指针大法
/*Since only constant memory is allowed, time cost is O(k) */
static struct ListNode*
Reverse(struct ListNode *begin, struct ListNode *end){
struct ListNode* prev = begin->next;
struct ListNode* curr = prev->next;

while(curr != end){
prev->next = curr->next;
curr->next = begin->next;
begin->next = curr;
curr = prev->next;
}
return prev;
}

struct ListNode*
reverseList(struct ListNode* head) {
if(head == NULL || head->next == NULL) return head;

struct ListNode *dummyHead = (struct ListNode *)malloc(sizeof(*dummyHead));
dummyHead->next = head;

struct ListNode *iter = head;

int count = 1;
while(iter->next != NULL){
iter = iter->next;
++count;
}
Reverse(dummyHead, iter->next);

return dummyHead->next;
}

/********************************************************************/
/********************************************************************/

/********************************************************************/
// List.c 是范性类 单链表
/********************************************************************/
//反转单链表中 begin 到 end 节点
static ListElmt*
tt_Reverse(ListElmt *begin, ListElmt *end){

ListElmt* prev = begin->next;
ListElmt* curr = prev->next;

while(curr != end){
prev->next = curr->next;
curr->next = begin->next;
begin->next = curr;
curr = prev->next;
}
return prev;
}

static ListElmt*
tt_reverseList(ListElmt* head) {
if(head == NULL || head->next == NULL) return head;

ListElmt *dummyHead = (ListElmt *)malloc(sizeof(*dummyHead));
dummyHead->next = head;

ListElmt *iter = head;
int count = 1;
while(iter->next != NULL){
iter = iter->next;
++count;
}
tt_Reverse(dummyHead, iter->next);
return dummyHead->next;
}

void
test_tt_reverseList(){
List l1;
list_init(&l1, free);
int *data ;
int array[15] = {100,200,300,400,500,600,700,800,900,1000};
for (int i = 0; i< 10; i++) {
if ((data = (int *)malloc(sizeof(int))) == NULL)
return ;
*data = array[i];
if (list_ins_next(&l1, NULL, data) != 0) //逐个插入元素
return;
}
print_list(&l1);
ListElmt *result = tt_reverseList(list_head(&l1));
printf("result->val===%d\n",*(int *)result->data);
print_listNode(result);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: