这个题目刚看到我还以为是反转链表(其实人家是相临节点的两两交换)
既然这样就比较一下吧
24 两两翻转链表
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes,
only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
① 递归法
class Solution {
public ListNode swapPairs(ListNode head) {
// 1. 终止条件:当前没有节点或者只有一个节点,肯定就不需要交换了
if (head == null || head->next == null) return head;
// 2. 调用单元
// 需要交换的两个节点是 head 和 head.next
ListNode firstnode = head;
ListNode secondnode = head->next;
// firstNode 连接后面交换完成的子链表
firstnode.next = swapPairs(secondnode->next);//该句必须要放到前面
//不然secondnode->next就被更新了
secondnode->next = firstnode;// secondNode 连接 firstNode
// 3. 返回值:返回交换完成的子链表
// secondNode 变成了头结点
return secondnode;
}
}
② 迭代
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode p = dummyHead;
while (p.next != null && p.next.next != null) {
ListNode node1 = p.next;
ListNode node2 = p.next.next;
p.next = node2;
node1.next = node2.next;
node2.next = node1;
p = node1;
}
return dummyHead.next;
}
}
206 反转链表
题目要求
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
① 迭代法
迭代法这里,我首先出现的问题是,直接用了head指针 ,看似没问题,但是你的头指针呢,head应该的指向null的,使用这个方法会导致head-> <-head.next形成环路。所以应该定义两个指针 pre、cur
while(head.next!=null){
tmp=head.next;
head.next.next=head;
head=tmp;
}
第2个问题,在循环中的选择的时候发生了如下问题(5.4.3.2.1)只返回5
while(cur.next!=null){
。。。。
}
return cur
想明白了,cur.next是在变化的呀,
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre=null;
ListNode cur=head;
while(cur!=null){
ListNode temp=cur.next;//是cur.next会发生变化,所以要用tmp暂存
cur.next=pre;
pre=cur;//注意这两句的顺序
cur=temp;
}
return pre;
}
}
② 递归法
class Solution {
public ListNode reverseList(ListNode head) {
//必须要判空,而且head和head.next的顺序不能变 []的时候出问题!
if(head==null|| head.next==null){
return head;
}
// 步骤 1: 先翻转 head 之后的链表
ListNode newhead=reverseList(head.next);
// 步骤 2: 再把原 node 节点后继结点的后继结点指向 head,head 的后继节点设置为空(防止形成环)
head.next.next=head;//反转之后的链表就找不到head.next这个节点了,因为返回的是
//新链表的头结点,所以要用head来处理递归之外的指针变化
head.next=null;
return newhead;
}
}