题目目录
1.反转链表
方法一:暴力改链表方向
思路就是直接把箭头全改为反向
要注意的是要三个结构体指针n1(要改的前一个), n2(要改的), n3(要改的后面一个),依次向后遍历就能完成。
代码如下 :
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
if(head == NULL)
{
return NULL;
}
struct ListNode* n1 = NULL;
struct ListNode* n2 = head;
struct ListNode* n3 = head->next;
while(n3 != NULL)
{
n2->next = n1;
n1 = n2;
n2 = n3;
n3 = n3->next;
}
n2->next = n1;
return n2;
}
方法二:迭代法
用尾插的方法迭代:
创建一个新的尾(NULL),原链表从左向右依次插入新链表就能完成反转,如图:
开始
过程
结束
要注意的是newHead的位置要改变到新链表头部,以返回新链表。
代码如下 :
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
if(head == NULL || head->next == NULL)
{
return head;
}
struct ListNode* newHead = NULL;
struct ListNode* cur = head;
struct ListNode* next = cur->next;
while(cur)
{
struct ListNode* next = cur->next;
cur->next = newHead;
newHead = cur;
cur = next;
}
return newHead;
}
2.链表的中间结点
方法一:暴力解法
遍历链表计算总共数目,结果 /2 就为中间值,再遍历到这个位置
代码如下 :
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* middleNode(struct ListNode* head){
int count = 0;
struct ListNode* cur = head;
while